Re: [RFC] Comparable: the revenge
| From: | Dennis Birkholz | Date: | Fri, 20 Feb 2015 10:04:18 +0000 |
| Subject: | Re: [RFC] Comparable: the revenge | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-83283@lists.php.net to get a copy of this message | ||
Hi Adam,
Am 19.02.2015 um 22:40 schrieb Adam Harvey:
> RFC: https://wiki.php.net/rfc/comparable
> PR: https://github.com/php/php-src/pull/1097
I see a little problem here by allowing any comparison. Comparing is
used for ordering, but you can easily construct ordering mechanisms that
simply don't work:
class A implements Comparable {
public $value;
function compareTo($other) {
if ($other instanceof A) {
return $this->value <=> $other->value;
} else {
return -1;
}
}
}
class B implements Comparable {
public $value;
function compareTo($other) {
if ($other instanceof B) {
return $this->value <=> $other->value;
} else {
return -1;
}
}
}
$a = new A();
$a->value = 1;
$b = new B();
$b->value = 2;
$a->compareTo($b); // -1
$b->compareTo($a); // -1
If you now have a mixed list of objects of A and B, the actual order in
the list completely depends whether A's compareTo() method is called or
B's compareTo() method.
I think comparison should always be symmetric:
$a < $b <=> $b > $a
Otherwise the behavior is nearly unpredictable/random.
As we have no method overloading, the only viable option I see is to
only allow comparison of objects of the same type.
Thanks
Dennis