How to use the instanceof operator in PHP?

by aniya.jaskolski , in category: PHP General , 2 years ago

How to use the instanceof operator in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by lizzie , 2 years 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.

Member

by lew , a year ago

@aniya.jaskolski 

That's correct! Just to add, the instanceof operator can also be used to check if an object is an instance of an interface. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
interface Animal {
    public function makeSound();
}

class Cat implements Animal {
    public function makeSound() {
        echo "Meow!";
    }
}

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


In this example, we have an interface Animal with a single method makeSound. The class Cat implements this interface and provides its own implementation of makeSound. We then create an object of Cat and use instanceof to check if it is an instance of Animal. The output will be:

1
The cat is an animal.


In this case, the instanceof operator returns true because Cat is an instance of Animal.