一句话不,没有__equals魔法。有一个完整的魔术方法列表
in the manual。
你可以做
$myObject1 == $myObject2
如果它们具有相同的属性和值,它们将被认为是相同的,并且是相同类的实例。
我经常希望这种类型的方法,但我认为一个更有用的方法是一个__compare()方法,它将被任何比较运算符,==,===等等存在于PHP的内置课程,可以在PHP internals wiki中看到,有一个例子说明如何在PHPInternals book中实现:
compare_objects
06001
Compares two objects. Used for the operators ==, !=, , ⇐ and >=.
The implementations should follow these rules – for any objects a, b and c that share the same compare handler:
我用来实现这一点的一个方法是实现一个可比较的界面,如:
interface Comparable
{
/**
* @param Comparable $other
* @param String $comparison any of ==, , ==, etc
* @return Bool true | false depending on result of comparison
*/
public function compareTo(Comparable $other, $comparison);
}