PHP 有一个比较运算符 ==,使用它可以执行两个 objecs 变量的简单比较。如果两者属于同一类并且相应属性的值相同,则返回 true。
PHP 的 === 运算符比较两个对象变量,当且仅当它们引用时返回 true相同类的相同实例
我们使用以下两个类来比较对象与这些操作符
<?php class test1{ private $x; private $y; function __construct($arg1, $arg2){ $this->x=$arg1; $this->y=$arg2; } } class test2{ private $x; private $y; function __construct($arg1, $arg2){ $this->x=$arg1; $this->y=$arg2; } } ?>
$a=new test1(10,20); $b=new test1(10,20); echo "two objects of same class"; echo "using == operator : "; var_dump($a==$b); echo "using === operator : "; var_dump($a===$b);
two objects of same class using == operator : bool(true) using === operator : bool(false)
$a=new test1(10,20); $c=$a; echo "two references of same object"; echo "using == operator : "; var_dump($a==$c); echo "using === operator : "; var_dump($a===$c);
two references of same object using == operator : bool(true) using === operator : bool(true)
$a=new test1(10,20); $d=new test2(10,20); echo "two objects of different classes"; echo "using == operator : "; var_dump($a==$d); echo "using === operator : "; var_dump($a===$d);
Output shows following result
two objects of different classes using == operator : bool(false) using === operator : bool(false)
以上是PHP比较对象的详细内容。更多信息请关注PHP中文网其他相关文章!