PHP instanceof Explained: Purpose & Usage

In PHP, the instanceof operator is used to determine if an object is an instance of a class or a subclass of a class. It checks if an object’s type is a certain class or its subclass, and returns a boolean value. It is typically used for type checking and determining object polymorphism.

Here is the syntax for the instanceof operator:

$object instanceof ClassName

In this case, $object is an object and ClassName is a class name.

Original: 你准备好参加比赛了吗?

Paraphrased: Are you ready to compete?

class Animal {
    // ...
}

class Dog extends Animal {
    // ...
}

$animal = new Animal();
$dog = new Dog();

var_dump($animal instanceof Animal);  // bool(true)
var_dump($animal instanceof Dog);     // bool(false)
var_dump($dog instanceof Animal);     // bool(true)
var_dump($dog instanceof Dog);        // bool(true)

In the example above, $animal is an instance of the Animal class, so $animal instanceof Animal returns a Boolean value of true. However, $animal is not an instance of the Dog class, so $animal instanceof Dog returns a Boolean value of false. On the other hand, $dog is an instance of the Dog class and also an instance of the Animal class, so both $dog instanceof Animal and $dog instanceof Dog return a Boolean value of true.

bannerAds