Concept Flow - Instanceof operator
Create object
Check if object is instance of class/interface
Return true
The instanceof operator checks if an object belongs to a class or implements an interface, returning true or false.
<?php class Animal {} class Dog extends Animal {} $dog = new Dog(); var_dump($dog instanceof Animal); ?>
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Create class Animal | N/A | Class Animal defined |
| 2 | Create class Dog extends Animal | N/A | Class Dog defined |
| 3 | Create object $dog = new Dog() | N/A | Object $dog created of class Dog |
| 4 | Check $dog instanceof Animal | $dog is Dog, Dog extends Animal | bool(true) |
| 5 | Output result | bool(true) | bool(true) printed |
| Variable | Start | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|
| $dog | undefined | object of Dog | object of Dog | object of Dog |
Instanceof operator syntax: $object instanceof ClassName Returns true if $object is instance of ClassName or subclass. Returns false otherwise. Used to check object type safely. Works with classes and interfaces.
instanceof operator do in PHP?instanceofinstanceof operator is used to check if a variable is an object of a certain class or subclass.$obj is an instance of class Car?instanceof syntaxvariable instanceof ClassName, without extra keywords or rearrangement.$a = new DateTime();
if ($a instanceof DateTime) {
echo 'Yes';
} else {
echo 'No';
}$a instanceof DateTime is true because $a is exactly a DateTime object.class Animal {}
class Dog extends Animal {}
$dog = new Dog();
if ($dog instanceof 'Animal') {
echo 'It is an animal';
}instanceof operator expects a class name without quotes, not a string.class Vehicle {}
class Car extends Vehicle {}
class Bike extends Vehicle {}
function checkVehicle($obj) {
if ($obj instanceof Car) {
return 'Car';
} elseif ($obj instanceof Vehicle) {
return 'Vehicle';
} else {
return 'Unknown';
}
}
$myBike = new Bike();
echo checkVehicle($myBike);Pass the test and this pattern moves unknown