0
0
PHPprogramming~10 mins

Instanceof operator in PHP - Step-by-Step Execution

Choose your learning style9 modes available
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.
Execution Sample
PHP
<?php
class Animal {}
class Dog extends Animal {}
$dog = new Dog();
var_dump($dog instanceof Animal);
?>
This code checks if the object $dog is an instance of the Animal class or its subclass.
Execution Table
StepActionEvaluationResult
1Create class AnimalN/AClass Animal defined
2Create class Dog extends AnimalN/AClass Dog defined
3Create object $dog = new Dog()N/AObject $dog created of class Dog
4Check $dog instanceof Animal$dog is Dog, Dog extends Animalbool(true)
5Output resultbool(true)bool(true) printed
💡 Instanceof check completes with true because Dog is subclass of Animal
Variable Tracker
VariableStartAfter Step 3After Step 4Final
$dogundefinedobject of Dogobject of Dogobject of Dog
Key Moments - 2 Insights
Why does $dog instanceof Animal return true even though $dog is created as Dog?
Because Dog is a subclass of Animal, so $dog is considered an instance of Animal too, as shown in execution_table step 4.
What happens if we check an object against an unrelated class?
The instanceof operator returns false, because the object is not an instance of that class or its parents, similar to the 'No' branch in concept_flow.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what is the result of $dog instanceof Animal?
Anull
Btrue
Cfalse
Derror
💡 Hint
Check the 'Result' column in execution_table row 4.
At which step is the object $dog created?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column for object creation in execution_table.
If Dog did not extend Animal, what would $dog instanceof Animal return?
Afalse
Btrue
Cnull
Derror
💡 Hint
Refer to concept_flow where 'No' branch returns false.
Concept Snapshot
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.
Full Transcript
This visual trace shows how the instanceof operator works in PHP. First, classes Animal and Dog are defined, with Dog extending Animal. Then, an object $dog is created from Dog. The operator checks if $dog is an instance of Animal. Because Dog inherits from Animal, the check returns true. The variable $dog holds the Dog object throughout. If checked against an unrelated class, instanceof would return false. This helps safely identify object types in code.