แนะนำตัว
PHP มีตัวดำเนินการเปรียบเทียบ == โดยใช้การเปรียบเทียบอย่างง่ายของสองตัวแปรวัตถุ คืนค่า จริง หากทั้งคู่อยู่ในคลาสเดียวกันและค่าของคุณสมบัติที่เกี่ยวข้องเหมือนกัน
ของ PHP === โอเปอเรเตอร์เปรียบเทียบตัวแปรอ็อบเจ็กต์สองตัวและคืนค่า จริง ต่อเมื่ออ้างถึงอินสแตนซ์เดียวกันของคลาสเดียวกัน
เราใช้สองคลาสต่อไปนี้เพื่อเปรียบเทียบวัตถุกับตัวดำเนินการเหล่านี้
ตัวอย่าง
<?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\n"; 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\n"; 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\n"; 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)