Re: [RFC] User-defined object comparison
| From: | Rowan Collins | Date: | Sat, 30 Jun 2018 23:07:34 +0000 |
| Subject: | Re: [RFC] User-defined object comparison | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-102544@lists.php.net to get a copy of this message | ||
On 30 June 2018 19:04:27 BST, Rudolf Theunissen <rudolf.theunissen@gmail.com> wrote:
>We're proposing the ability for a user to determine how a class should
>be
>compared to another value. The ability to change the semantics of the
>comparison operators is an unavoidable side effect.
Absolutely, I agree with the intent of this RFC. I think what I was suggesting is that if people in
future want to overload the operators specifically, we would want to provide an overload for
<=> that was separate from __compareTo, so that you could overload that without breaking
things like sorting.
>> I think __compareTo() and __equals() could act more like a return
>type
>hint, and either throw a TypeError straight away, or attempt to coerce
>to
>the correct type and throw a TypeError on failure.
>
>Currently they do attempt to convert to boolean and integer,
>respectively,
>but that doesn't achieve much because you can still return nothing in
>either case and the coercion would be 0 and false.
Apologies if this is covered in the RFC, but does that apply wherever they are used? For instance,
what will the following code do?
class SpaceStation {
public $shape;
public function __construct($shape='[]') {
$this->shape = $shape;
}
public function __compareTo($other) {
return new self($this->shape . '>=<' . $other->shape);
}
}
$a = new SpaceStation;
$b = new SpaceStation;
$c = $a <=> $b; // Error? 0?
echo $c->shape; // or will this echo '[]>=<[]'?
$d = $a < $b; // Same result?
$list = [$a, $b, $c, $d];
sort($list); // Or will the error only be raised here?
>The decision whether to accept this will come down to the trade-off
>between
>flexibility and potential for misuse.
Absolutely, and for what it's worth (which isn't much) I'm +1 on this, if it's
not documented as operator overloading (which I think is a separate feature) and can't be used
to produce values outside the expected type (due to coercion or errors).
Regards,
--
Rowan Collins
[IMSoP]