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中文網其他相關文章!