在 PHP 中,instanceof 關鍵字用于檢查一個對象是否屬于某個類或接口的實例。在繼承關系中,這個關鍵字非常有用,因為它允許你在運行時確定一個對象是否屬于特定的子類或父類。
以下是一個簡單的例子,說明如何在繼承中使用 instanceof:
class Animal {
public function makeSound() {
echo "The animal makes a sound";
}
}
class Dog extends Animal {
public function makeSound() {
echo "The dog barks";
}
}
$dog = new Dog();
if ($dog instanceof Animal) {
$dog->makeSound(); // 輸出 "The dog barks"
} else {
echo "The object is not an instance of Animal";
}
if ($dog instanceof Dog) {
$dog->makeSound(); // 輸出 "The dog barks"
} else {
echo "The object is not an instance of Dog";
}
在這個例子中,我們定義了一個名為 Animal 的基類和一個名為 Dog 的子類。Dog 類繼承了 Animal 類并重寫了 makeSound 方法。
接下來,我們創建了一個名為 $dog 的 Dog 類的實例。然后,我們使用 instanceof 關鍵字檢查 $dog 是否是 Animal 類和 Dog 類的實例。在這種情況下,$dog 是 Animal 類和 Dog 類的實例,所以當我們調用 makeSound 方法時,它會輸出 “The dog barks”。