บทนำ
ใน PHP สามารถตรวจสอบได้ว่าตัวแปรที่กำหนดเป็นอ็อบเจ็กต์ของคลาสเฉพาะหรือไม่ สำหรับวัตถุประสงค์นี้ PHP มีตัวดำเนินการ instanceof
รูปแบบไวยากรณ์
$var instanceof class
ตัวดำเนินการนี้คืนค่า TRUE ถ้า $var เป็นอ็อบเจ็กต์ของคลาส มิฉะนั้นคืนค่า FALSE
ตัวอย่าง
ในตัวอย่างต่อไปนี้ ตัวดำเนินการ instanceof ตรวจสอบว่าอ็อบเจ็กต์ที่กำหนดเป็นของคลาสผู้ใช้กำหนด testclass
ตัวอย่าง
<?php class testclass{ //class body } $a=new testclass(); if ($a instanceof testclass==TRUE){ echo "\$a is an object of testclass"; } else { echo "\$a is not an object of testclass"; } ?>
ผลลัพธ์
$a is an object of testclass
เพื่อตรวจสอบว่าอ็อบเจ็กต์หนึ่งไม่ใช่อินสแตนซ์ของคลาส ใช้ตัวดำเนินการ !
ตัวอย่าง
<?php class testclass{ //class body } $a=new testclass(); $b="Hello"; if (!($b instanceof testclass)==TRUE){ echo "\$b is not an object of testclass"; } else { echo "\$b is an object of testclass"; } ?>
ผลลัพธ์
$b is not an object of testclass
ตัวดำเนินการ instanceof ยังตรวจสอบได้ว่าตัวแปรเป็นอ็อบเจ็กต์ของคลาสพาเรนต์ (parent class) หรือไม่:
ตัวอย่าง
<?php class base{ //class body } class testclass extends base { //class body } $a=new testclass(); var_dump($a instanceof base) ?>
ผลลัพธ์
bool(true)
ยังสามารถตรวจสอบได้ว่าตัวแปรเป็นอินสแตนซ์ของอินเตอร์เฟซหรือไม่:
ตัวอย่าง
<?php interface base{ } class testclass implements base { //class body } $a=new testclass(); var_dump($a instanceof base) ?>
ผลลัพธ์
bool(true)