Is there a pattern or magic method you can use in PHP to define when to compare two instances of a class?
For example, in Java I could easily override the equa
Basically, as everyone says, this will do:
$object1 == $object2
Compares type and properties.
But what I do in this cases, when I want to personalize my equality methods, is implement the magic method __toString() in the classes I want to assert equality.
class Car {
private $name;
private $model;
...
public function __toString() {
return $this->name.", ".$this->model;
}
}
And then when I want to do the comparision I just do this:
$car1->toString() === $car2->toString()
And that will compare if the two instances have the same attributes.
The other option (as halfer states in the comments) is implement an equal method that asserts equality of another instance of the same class. For example:
class Car {
private $name;
private $model;
...
public function equals(Car $anotherCar) {
if($anotherCar->getName() !== $this->name) {
return false;
}
if($anotherCar->getModel() !== $this->model) {
return false;
}
...
return true;
}
}