gpt4 book ai didi

php - 使用 == 运算符在对象比较期间忽略选定的类成员

转载 作者:行者123 更新时间:2023-12-02 17:18:45 24 4
gpt4 key购买 nike

PHP 提供了一种非常好的对象比较方法。

class People {
public $name;
}

$p0 = new People();
$p1 = new People();

$p0->name = 'ali';
$p1->name = 'ali';

// equal
if ($p0 == $p1) {
echo 'equal' . "\n";
} else {
echo 'diff' . "\n";
}

但是,有时,我希望在比较过程中忽略一些类成员。

class People {
public $id;
public $name;
}

$p0 = new People();
$p1 = new People();

$p0->id = 0; // Can we ignore this id during == comparison?
$p1->id = 1; // Can we ignore this id during == comparison?
$p0->name = 'ali';
$p1->name = 'ali';

// diff. As $p0->id != $p1->id. How can we ignore id during == comparison?
if ($p0 == $p1) {
echo 'equal' . "\n";
} else {
echo 'diff' . "\n";
}

是否有办法让我要求 == 运算符忽略选定的类成员?

最佳答案

您不能在 PHP 中重载运算符。有一个PECL extension允许它,但更容易(也更便携)为您的对象提供一个 equals() 方法,然后通过它进行比较,例如

class People

public function equals(People $people)
{
return $this->name === $people->name;
}
}

关于php - 使用 == 运算符在对象比较期间忽略选定的类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21926600/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com