PHP Reference ยท Functions and Classes
Comparing objects in PHP
How PHP compares objects: == checks class and property values, === checks identity, how < and > order objects, clones, enums and common pitfalls.
PHP has two ways to ask whether two objects are "the same". The identity operator === is true only when both variables point at the very same instance. The equality operator == is true when the objects are instances of the same class and all their properties are equal (compared with == again).
Because objects are handles, assigning one to another variable does not copy it: both variables now refer to one instance, so === is true. clone creates a second instance with the same property values, so == is true but === is false.
$a == $b; // same class, equal property values $a === $b; // the very same instance
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
How comparison works
==first checks that both operands are objects of the same class, then compares their properties one by one with==. Different classes givefalse, even with identical properties.===compares object identity. It never looks at properties.<,>,<=>work on objects of the same class: PHP compares the properties in declaration order and stops at the first one that differs. Objects of different classes are "uncomparable" and every ordering comparison returnsfalse.- Enum cases are singletons, so
===and==agree. Enums cannot be compared with<meaningfully.
Usage notes
- Prefer
===to test "is this the instance I expect". Use==only when you really want value equality. - Loose property comparison is risky.
"1" == 1inside a property makes two objects equal, and untyped properties can surprise you. Typed properties are coerced on assignment, which reduces the problem. - Circular references. Comparing two objects that reference each other with
==can end in a fatal error ("Nesting level too deep"). Compare identities or write an explicitequals()method instead. - Write your own
equals()when only some properties matter (for example anid). PHP has no operator overloading, so==cannot be customized. - Closures compare equal only to themselves (
===). - Built-in classes can define their own rules:
DateTimeandDateTimeImmutableobjects compare by the moment in time they represent, so$a < $bworks for dates. - Do not use objects as array keys. Use
spl_object_id()orSplObjectStoragewhen you need identity-based lookup. - Sorting arrays of objects with
sort()uses the same ordering rules; for a specific order useusort()with a callback.