Simon Simon - 9 months ago 40
PHP Question

Is there a __equals method in PHP like there is in Java?

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

method and create a custom way of checking and compare two instances.

Answer Source

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:-


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
     * @param String $comparison any of ==, <, >, =<, >=, etc
     * @return Bool true | false depending on result of comparison
    public function compareTo(Comparable $other, $comparison);

The details of object comparison, and everything else OOP related can be found here

This may be implemented in PHP 7.