SO,
The problem
It's not well-known, but PHP allows to compare objects - and not just on equality ==
- but on <
and >
too. But - how it works? So if I want to create comparable objects - what restrictions/rules they should follow?
Most useful case is with DateTime()
objects - they hold certain timestamp and they could be compared (and this has logical sense). On lxr there's some explanation for DateTime
. But what about common case?
I have:
class C
{
protected $holder;
protected $mirror;
public function __construct($h = null)
{
$this->holder=$h;
$this->mirror=-1*$h;
}
}
$one = new C(1);
$two = new C(2);
//false, false, true: used $holder
var_dump($one>$two, $one==$two, $one<$two);
-if I'll change properties declaration order, it will use $mirror
:
class C
{
//only order changed:
protected $mirror;
protected $holder;
public function __construct($h = null)
{
$this->holder=$h;
$this->mirror=-1*$h;
}
}
$one = new C(1);
$two = new C(2);
//true, false, false: used $mirror
var_dump($one>$two, $one==$two, $one<$two);
So it seems one of the 'rules' is that it will use first declared property. But why is it using protected
property at all is not clear to me too.
Now, more complex sample:
class Test
{
protected $a;
protected $b;
function __construct($a, $b)
{
$this->a = $a;
$this->b = $b;
}
}
$x = new Test(1, 2);
$y = new Test(1, 3);
// true, false, false
var_dump($x < $y, $x == $y, $x > $y);
$x = new Test(3, 1);
$y = new Test(2, 1);
// false, false, true
var_dump($x < $y, $x == $y, $x > $y);
-so it will use first not-equal property for comparison. But code snippets above are only some cases. I want to know exactly how it's happening and why. Thus,
Question
Is: how it works? I mean, more detailed:
- Can I rely on fact, that PHP will use first not-equal property for comparison?
- What will be done if count of properties isn't equal? (i.e. some property was dynamically added to instance during code execution)
- Can I treat
protected
/private
properties as to be counted for such comparison always?
e.t.c. - so if there are some additional conditions/restrictions/rules that will affect result - please, post. Documentation states only for ==
/===
comparison. Also, comparison of instances of different classes is out of the issue since it'll return false
(obviously).