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

发布于 2024-12-14 08:47:41 字数 578 浏览 2 评论 0原文

我的梦想之一是在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月隐月明月朦胧 2024-12-21 08:47:41

不,不是。实现此目的的常见方法是使用 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)
?>

我认为这与:

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

无论如何,我的示例即使使用 == 运算符也能正常工作,因为它将比较所有属性的值。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文