0

How PHP compare custom entities ?

e.g.

Class Foo {
    private $bar;

    public function __construct($bar)
    {
        $this->bar = $bar;
    }
}

$a = new Foo(12);
$b = new Foo('abc');

var_dump($a < $b);
var_dump($a == $b);
var_dump($a > $b);

Is there a function to override in Foo to modify the comportement of <, == and > ?

Bouffe
  • 770
  • 13
  • 37

1 Answers1

1

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.

Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96