RE: [PHP-DEV] [RFC] Combined Comparison Operator
| From: | Christian Stoller | Date: | Fri, 14 Feb 2014 07:18:53 +0000 |
| Subject: | RE: [PHP-DEV] [RFC] Combined Comparison Operator | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-72582@lists.php.net to get a copy of this message | ||
>>
>> Why not using
$a - $b instead of $a
>> <=> $b?
>>
>>
>> Simon J Welsh <simon@simon.geek.nz> 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