One of my dreams is to use python rich comparison (something like __eq__) on php objects.
class A {
public $a = 1;
public function __eq__($other) {
return $this->a == $other->a;
}
}
class B {
public $a = 2;
public function __eq__($other) {
return $this->a == $other->a;
}
}
class C {
public $a = 1;
public function __eq__($other) {
return $this->a == $other->a;
}
}
$a = new A();
$b = new B();
$c = new C();
echo $a == $b; //false
echo $a == $c; //true
I’d like to have some smart mechanism to fast-compare models (objects) on database id, for example.
Is it possible in some way in PHP?
No, it isn’t. A common way to achieve this is to use an
equals()method, but there isn’t any magic method. You’ll have to call it manually. For example:Which, I think, isn’t much different from:
Anyway, my example will work even using the
==operator, since it will compare the values of all the properties.