php中是否可以进行python丰富的比较?
我的梦想之一是在 php 对象上使用 python 丰富的比较(类似于 __eq__ )。
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 中是否有可能以某种方式实现?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,不是。实现此目的的常见方法是使用
equals()
方法,但没有任何神奇的方法。您必须手动调用它。例如:我认为这与:
无论如何,我的示例即使使用
==
运算符也能正常工作,因为它将比较所有属性的值。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:Which, I think, isn't much different from:
Anyway, my example will work even using the
==
operator, since it will compare the values of all the properties.