Comparing objects using the PHP spaceship operator (<=>
) follows the same rules as with other comparison operators (as outlined in the official PHP docs) — i.e., the following three rules apply:
-
Objects of Different Classes Are Incomparable: Objects of different classes cannot be compared to each other. In this instance,
1
is always returned. For example:class Foo {} class Bar {} echo new Foo() <=> new Bar(); // 1 echo new Bar() <=> new Foo(); // 1
-
Objects of Same Class With Different Property Values Return First Non-Equal Result: If both objects are of the same class with different property values, then object properties are compared in the order in which they are defined in the class using the equality operator (
==
). If there's a difference in the property values, the comparison stops, and the result of that comparison is returned. For example:class Person { public function __construct( private string $name, private int $age, ) {} } $person1 = new Person('Wayne', 23); $person2 = new Person('Jane', 25); echo $person1 <=> $person2; // 1 echo $person2 <=> $person1; // -1
In this example,
$person1
is greater than$person2
because of the string comparison of thename
property — i.e., "Wayne
" is lexicographically greater than "Jane
". No further comparisons are done beyond that, as it's the first non-equal property, and its result is returned.Consider another example, where both instances of the
Person
class have the same value for thename
property, but a different value for theage
property:class Person { public function __construct( private string $name, private int $age, ) {} } $person1 = new Person('John', 23); $person2 = new Person('John', 25); echo $person1 <=> $person2; // -1 echo $person2 <=> $person1; // 1
In this case, the result of the numeric comparison of the second property is returned since the values of the first property are the same for both objects. This means that
$person1
is smaller than$person2
in comparison. -
Objects of Same Class With Same Property Values Are Equal: If both objects are of the same class with same properties and values, then they are considered equal. For example:
class Person { public function __construct( private string $name, private int $age, ) {} } $person1 = new Person('John', 23); $person2 = new Person('John', 23); echo $person1 <=> $person2; // 0 echo $person2 <=> $person1; // 0 echo $person1 <=> $person1; // 0 echo $person2 <=> $person2; // 0
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.