Re: [RFC] User-defined object comparison
| From: | Rowan Collins | Date: | Sun, 01 Jul 2018 21:00:39 +0000 |
| Subject: | Re: [RFC] User-defined object comparison | ||
| References: | 1 2 3 4 5 6 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-102550@lists.php.net to get a copy of this message | ||
On 1 July 2018 19:45:03 BST, Rudolf Theunissen <rudolf.theunissen@gmail.com> wrote:
>>
>> 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 it would be confusing to have both, or to have <=> not be
>aligned
>with __compareTo, because they are semantically equivalent. By
>overloading
><=>, you have to also override comparison. Separating those is a recipe
>for
>confusion.
That's the point though: with operator overloading as defined in many languages, they're
only semantically equivalent if the person overloading the operator wants them to be. The most
well-known example is probably the C++ operator >> which for primitives is a bit shift, but is
overloaded for input and output to streams.
If, on the other hand, operator overloading was added but constrained by the language to certain
return values, there would be very little to be gained by overloading each comparison separately -
all the extra overloads would have to return boolean anyway.
>When you use the
<=> operator, the return value is
>normalised to
>either
>-1, 0 or 1 which is consistent with the current behaviour. So the
>object
>you're returning in compareTo will be converted to an
>integer(1)
That makes perfect sense to me, thanks. Just to reiterate, it's *not* what fans of free-form
operator overloading would want, but I think it's the right behaviour for this feature.
>One thing that your example brings up is that <=> is not
>exactly
>equivalent to calling __compareTo directly, which would just
>return
>the
>raw value.
Yeah, that's a good point. Directly calling magic methods is always a bit peculiar, but I think
a note in the manual is probably enough.
Regards,
--
Rowan Collins
[IMSoP]