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
In a word? No. There is no __equals magic method. There is a complete list of the magic methods in the manual.
You can do
$myObject1 == $myObject2
which will consider them equal if they have the same attributes and values, and are instances of the same class.
I have often wished for this type of method myself, but I think that a more useful one would be a __compare() method which would be called for any comparison operator <, >, ==, ===, etc it already exist for PHP's inbuilt classes as can be seen in the PHP internals wiki and there is an example of how it could be implemented in the PHPInternals book:-
compare_objects
int (*compare)(zval *object1, zval *object2 TSRMLS_DC)Compares two objects. Used for the operators ==, !=, <, >, ⇐ and >=. The implementations should follow these rules – for any objects a, b and c that share the same compare handler:
One way I have used to achieve this is to implement a Comparable interface, something like:-
interface Comparable
{
/**
* @param Comparable $other
*
* @return Int -1, 0 or 1 Depending on result of comparison
*/
public function compareTo(Comparable $other);
}
The details of object comparison, and everything else OOP related can be found here http://www.php.net/manual/en/language.oop5.php.
This may be implemented in PHP 7.
There is now an implementation of this that you can install using composer. https://github.com/Fleshgrinder/php-comparable