Re: [RFC] Combined Comparison Operator

From: Date: Thu, 13 Feb 2014 18:04:34 +0000
Subject: Re: [RFC] Combined Comparison Operator
References: 1 2 3 4  Groups: php.internals 
Request: Send a blank email to [email protected] to get a copy of this message
On 2/13/14, 12:14 PM, Pierre Joye wrote:
Hi David, Thanks for this proposal. On Feb 13, 2014 10:30 PM, "Davey Shafik" <[email protected]> wrote:
On 2/13/14, 2:19 AM, Christian Stoller wrote:
Davey Shafik <[email protected]> wrote:
This adds a new operator "(expr) <=> (expr)" that returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater. It works with all types (just as well as <, <=, >=, > work) and is great for usort() callbacks for example.
Why not using $a - $b instead of $a <=> $b? Simon J Welsh <[email protected]> wrote:
The only real case I see for this is to save some boilerplate when dealing with arrays. Strings have strcmp(), numbers have subtraction And when you’re sorting objects, you probably want to be doing the comparison on some string/numeric property.
Agreed! It would make more sense to write a comparison function for
arrays/objects.
Best regards Christian
This operator DOES work on arrays/objects. The fact it also works on
scalar values is a bonus if that's how you want to look at it :P This new operator doea not look too useful to me but here is one comment about objects handling: It compares only values, seems to be the only solution but the actual usage for that is rather inexistent as it compares apples and pears, or am I missing something? Cheers, Pierre
So, this behavior can definitely be changed — preserving the current behavior of == for the 0 value, and then we can go two different ways for 1/-1: - Compare only like-for-like keys, ignoring extra keys - Compare like-for-like keys, and count the number of additional keys are being great. So: if they match on all common keys, but left has 3 additional keys, and right has 4, right is greater than left. It's definitely tough to get the semantics right. But: the behavior is also currently identical to $obj <= $obj2, etc. I felt that consistency was most important. The logical next step with this operator is to add a "Comparable" "interface" like ruby (not saying it has to be an interface, magic method also works), that allows the objects themselves to define the comparison behavior, so you could do: class Foo {
    function __compare($right) {
         // logic here
    }
} $left = new Foo; $right = new Foo; $left <=> $right; // Same as $left->__compare($right);

Thread (20 messages)

« previous php.internals (#72560) next »