Re: Object comparison
| From: | Nathan Nobbe | Date: | Sat, 10 Nov 2012 03:46:37 +0000 |
| Subject: | Re: Object comparison | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-63797@lists.php.net to get a copy of this message | ||
On Fri, Nov 9, 2012 at 2:00 PM, jpauli <jpauli@php.net> wrote:
> On Fri, Nov 9, 2012 at 2:18 PM, Christian Stoller <stoller@leonex.de>
> wrote:
> > I would like to place a suggestion for comparing objects (I hope it is
> no problem, because this does not have anything to do with Sara's question
> - but it came to my mind when I read her mail). It would be a great feature
> if objects could be compared to other objects with ">", "<" and the
> other
> operators, like it is suggested in RFC
> https://wiki.php.net/rfc/comparable
> > The DateTime class offers this feature - it would be nice if this could
> be made usable for userland classes/objects, too.
>
>
> I really like that idea, and the patch looks pretty good and looks
> backward compatible.
> I'm +1 with it
>
> I'm also +1 with patching the doc to describe the full default compare
> behavior.
>
Another spot in the docs I would enjoy discussion about <,>,>=,<= comparing
two objects:
http://php.net/manual/en/language.oop5.object-comparison.php
I notice this behavior is suggested in a comment for use in an
array_uintersect callback:
http://php.tonnikala.org/manual/el/function.array-uintersect.php#72841
Indeed, trying to intersect two arrays of objects with a user callback
'works' with the > comparison operator, but maybe this is just luck, or
subject to BC break later?
<?php
class myclass { function __construct($name) { $this->name = $name; } }
$o1 = new myclass('o1');
$o2 = new myclass('o2');
$o3 = new myclass('o3');
$o4 = new myclass('o4');
$a1 = array($o1, $o2, $o3);
$a2 = array($o3, $o2, $o4);
var_dump(array_uintersect($a1, $a2, function($v1, $v2) {
if($v1 === $v2)
return 0;
if($v1 > $v2)
return 1;
return -1;
}));
I'd expect the > comparison there to be roughly equivalent
to if(spl_object_hash($v1) > spl_object_hash($v2)), no? Info on the
default behavior here would be nice.
-nathan