In regards to comparing objects in PHP SPL, the only comparison that makes sense is object equality (==
or ===
). These behave like you would expect them to; ==
will be true if the two objects are of the same class and whose attributes have the same values. ===
will only be true if two objects being compared are the same instance.
There is no built-in Comparable
interface for you to use or magic __compare
method that would override the default behavior for the other comparison operators. You can, however, make your own interface if you wish:
// From @vascowhite: http://stackoverflow.com/a/17008682/697370
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);
}
There is a PHP RFC that is currently 'under discussion' in regards to PHP7 (it was last updated 2015-02-19) that wishes to pull in a Comparable
interface to the SPL.