是否可以在php中进行python丰富的比较?

是否可以在php中进行python丰富的比较?,php,python,comparison,comparable,Php,Python,Comparison,Comparable,我的梦想之一是在php对象上使用python丰富的比较(类似于\uuuuueq\uuuu) 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 ==

我的梦想之一是在php对象上使用python丰富的比较(类似于
\uuuuueq\uuuu

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 
例如,我希望有一些智能机制来快速比较数据库id上的模型(对象)


在PHP中,它在某种程度上是可能的吗?

不,它不是。实现这一点的常用方法是使用
equals()
方法,但没有任何神奇的方法。你必须手动调用它。例如:

<?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)
?>

无论如何,我的示例甚至可以使用
==
操作符,因为它将比较所有属性的值。

不幸的是,没有。PHP的对象模型非常初级。像
if(object1.isEquals(object2))
var_dump($user1 == $user2);
var_dump($user2 == $user1);