在PHP中,instanceof
關鍵字用于檢查一個對象是否屬于某個類或接口的實例
<?php
class Animal {}
class Dog extends Animal {}
$dog = new Dog();
if ($dog instanceof Animal) {
echo "The object is an instance of Animal.";
} else {
echo "The object is not an instance of Animal.";
}
?>
在這個例子中,我們定義了兩個類:Animal
和Dog
。Dog
類繼承了Animal
類。然后我們創建了一個Dog
類的實例,并將其賦值給變量$dog
。
接下來,我們使用instanceof
關鍵字檢查$dog
是否是Animal
類的實例。如果是,我們輸出"The object is an instance of Animal.“,否則輸出"The object is not an instance of Animal.”。
在這個例子中,輸出將是:“The object is an instance of Animal.”,因為Dog
類是Animal
類的子類,所以$dog
是Animal
類的實例。