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 equals
method and create a custom way of checking and compare two instances.
Equal Operator ==The comparison operator called Equal Operator is the double equal sign “==”. This operator accepts two inputs to compare and returns true value if both of the values are same (It compares only value of variable, not data types) and return a false value if both of the values are not same.
equals() method in Java. Both equals() method and the == operator are used to compare two objects in Java. == is an operator and equals() is method. But == operator compares reference or memory location of objects in a heap, whether they point to the same location or not.
== Operator: This operator is used to check the given values are equal or not. If yes, it returns true, otherwise it returns false. === Operator: This operator is used to check the given values and its data type are equal or not. If yes, then it returns true, otherwise it returns false.
In java both == and equals() method is used to check the equality of two variables or objects. == is a relational operator which checks if the values of two operands are equal or not, if yes then condition becomes true. equals() is a method available in Object class and is used to compare objects for equality.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With