Re: [RFC] Combined Comparison Operator

From: Date: Fri, 14 Feb 2014 10:06:32 +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 Fri, 14 Feb 2014 11:18:53 +0400, Christian Stoller <[email protected]> wrote:

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 - Davey
That's why I said, it would make more sense to add a new function for comparing arrays and objects. Why adding a new comparison operator if we could achieve the same with one or two additional functions? And I am not sure, if this is not already possible nowadays. For arrays you could do: array_sum($array1) - array_sum($array2) And for objects you can define a "sum" method on your objects or a trait e.g. trait SummableTrait {
    public function sum() {
        $sum = 0;
        foreach (get_object_vars($this) as $value) {
            $sum += $value;
        }
        return $sum;
} } You only have to use this trait in your classes and then you can do: $object1->sum() - $object2->sum() Et voilà :-) Christian
Hi, DateTime is the problem here

Thread (20 messages)

« previous php.internals (#72587) next »