Search code examples
phppythoncomparisoncomparable

Is it possible to have python rich comparison in php?


One of my dreams is to use python rich comparison (something like __eq__) on php objects.

class A {
  public $a = 1;

  public function __eq__($other) {
      return $this->a == $other->a;
  }

}


class B {
  public $a = 2;

  public function __eq__($other) {
      return $this->a == $other->a;
  }

}


class C {
  public $a = 1;

  public function __eq__($other) {
      return $this->a == $other->a;
  }

}

$a = new A();
$b = new B();
$c = new C();

echo $a == $b; //false
echo $a == $c; //true 

I'd like to have some smart mechanism to fast-compare models (objects) on database id, for example.

Is it possible in some way in PHP?


Solution

  • No, it isn't. A common way to achieve this is to use an equals() method, but there isn't any magic method. You'll have to call it manually. For example:

    <?php
    class User
    {
        private $id;
    
        public function __construct($id)
        {
            $this->id = $id;
        }
    
        public function getId()
        {
            return $this->id;
        }
    
        public function equals(User $user)
        {
            return $this->getId() === $user->getId();
        }
    }
    
    $user1 = new User(1);
    $user2 = new User(2);
    
    var_dump($user1->equals($user2)); // bool(false)
    var_dump($user2->equals($user1)); // bool(false)
    ?>
    

    Which, I think, isn't much different from:

    var_dump($user1 == $user2);
    var_dump($user2 == $user1);
    

    Anyway, my example will work even using the == operator, since it will compare the values of all the properties.