บทนำ
PHP มีออปเปอเรเตอร์เปรียบเทียบสองตัวสำหรับออบเจ็กต์:
- == (Equality) - คืนค่า true ถ้าทั้งสองเป็นคลาสเดียวกัน และค่าพร็อพเพอร์ตีที่ตรงกันทุกคู่มีค่าเท่ากัน
- === (Identity) - คืนค่า 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\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)
ตัวอย่าง: สอง Reference ของออบเจ็กต์เดียวกัน
<?php $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)
ตัวอย่าง: สองออบเจ็กต์ของคลาสต่างกัน
<?php $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)
สรุป
| สถานการณ์ | == (Equality) | === (Identity) |
|---|---|---|
| ออบเจ็กต์สองตัว คลาสเดียวกัน ค่าพร็อพเพอร์ตีเท่ากัน | true | false |
| Reference สองตัวของออบเจ็กต์เดียวกัน | true | true |
| ออบเจ็กต์สองตัว คลาสต่างกัน (แม้ค่าจะเท่ากัน) | false | false |