How to use the instanceof operator in PHP?

by aniya.jaskolski , in category: PHP General , 6 months ago

How to use the instanceof operator in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 6 months ago

@aniya.jaskolski 

In PHP, the instanceof operator is used to determine whether an object is an instance of a particular class or a subclass of that class. The instanceof operator returns a Boolean value, true if the object is an instance of the specified class or false otherwise.


The syntax for using instanceof in PHP is as follows:

1
$object instanceof ClassName


Here, $object is the object you want to check, and ClassName is the name of the class you want to check against.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Animal {
    public $name;
}

class Cat extends Animal {
    public $breed;
}

$cat = new Cat();
if ($cat instanceof Animal) {
    echo "The cat is an animal.";
}
if ($cat instanceof Cat) {
    echo "The cat is a cat.";
}


In this example, we have two classes, Animal and Cat. Cat is a subclass of Animal. We create an object of Cat class and then use instanceof to check if the object is an instance of Animal or Cat class. The output will be:

1
2
The cat is an animal.
The cat is a cat.


Here, the first if statement is true because Cat is a subclass of Animal, so $cat is also an instance of Animal. The second if statement is also true because $cat is an instance of Cat.