让==运算符在对象比较期间忽略选定的类成员

时间:2014-02-21 06:09:57

标签: php

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";
}

如果我有任何方法让==运营商忽略选定的班级成员?

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:1)

您只需直接与name个对象进行比较

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