PHP 比較物件
簡介
PHP 有一個比較運算子 ==,可用該運算子執行兩個物件變數的簡單比較。如果兩個變數屬於同一類別,並且對應屬性的值也相同,則該運算子將返回 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);
輸出
輸出顯示以下結果
two objects of different classes using == operator : bool(false) using === operator : bool(false)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP