0
0
PHPprogramming~5 mins

Instanceof operator in PHP

Choose your learning style9 modes available
Introduction

The instanceof operator helps you check if an object belongs to a certain class or type. It is like asking, "Is this object a kind of this class?"

When you want to confirm an object is of a specific class before using its methods.
When you have different types of objects and want to handle them differently.
When you want to avoid errors by checking an object's type before calling class-specific code.
When working with inheritance and you want to check if an object is an instance of a parent or child class.
Syntax
PHP
$object instanceof ClassName

The operator returns true if $object is an instance of ClassName or its subclass.

It returns false if $object is not an object or not related to ClassName.

Examples
Checks if $dog is an object of class Animal or a subclass.
PHP
$dog instanceof Animal
Runs code only if $car is a Vehicle object.
PHP
if ($car instanceof Vehicle) {
    echo "This is a vehicle.";
}
Stores true or false depending on whether $var is an instance of StringClass.
PHP
$isString = $var instanceof StringClass;
Sample Program

This program creates two objects: $dog from class Dog which extends Animal, and $car from class Car. It checks if each object is an instance of Animal. Since Dog is a subclass of Animal, the first check is true. The Car object is unrelated, so the second check is false.

PHP
<?php
class Animal {}
class Dog extends Animal {}
class Car {}

$dog = new Dog();
$car = new Car();

if ($dog instanceof Animal) {
    echo "Dog is an Animal\n";
} else {
    echo "Dog is NOT an Animal\n";
}

if ($car instanceof Animal) {
    echo "Car is an Animal\n";
} else {
    echo "Car is NOT an Animal\n";
}
OutputSuccess
Important Notes

The instanceof operator works only with objects, not with simple types like strings or integers.

It also returns true if the object is an instance of a subclass of the given class.

Summary

instanceof checks if an object belongs to a class or its subclass.

It helps avoid errors by confirming object types before using them.

Returns true or false based on the check.