Bird
Raised Fist0
PHPprogramming~10 mins

Instanceof operator in PHP - Step-by-Step Execution

Choose your learning style10 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.

Practice

(1/5)
1. What does the instanceof operator do in PHP?
easy
A. Creates a new instance of a class
B. Checks if an object is an instance of a specific class or its subclass
C. Deletes an object from memory
D. Converts an object to a string

Solution

  1. Step 1: Understand the purpose of instanceof

    The instanceof operator is used to check if a variable is an object of a certain class or subclass.
  2. Step 2: Differentiate from other operations

    It does not create, delete, or convert objects; it only checks their type.
  3. Final Answer:

    Checks if an object is an instance of a specific class or its subclass -> Option B
  4. Quick Check:

    instanceof checks object type [OK]
Hint: Remember: instanceof checks object type, not creation or deletion [OK]
Common Mistakes:
  • Confusing instanceof with object creation
  • Thinking instanceof deletes objects
  • Assuming instanceof converts objects to strings
2. Which of the following is the correct syntax to check if $obj is an instance of class Car?
easy
A. if ($obj instance Car) {}
B. if ($obj is Car) {}
C. if (instanceof $obj Car) {}
D. if ($obj instanceof Car) {}

Solution

  1. Step 1: Recall correct instanceof syntax

    The correct syntax is: variable instanceof ClassName, without extra keywords or rearrangement.
  2. Step 2: Check each option

    if ($obj instanceof Car) {} matches the correct syntax exactly. Others have wrong keywords or order.
  3. Final Answer:

    if ($obj instanceof Car) {} -> Option D
  4. Quick Check:

    Correct instanceof syntax [OK]
Hint: Syntax is always: variable instanceof ClassName [OK]
Common Mistakes:
  • Using 'is' instead of 'instanceof'
  • Reversing order of variable and class
  • Adding extra keywords inside condition
3. What will be the output of the following PHP code?
$a = new DateTime();
if ($a instanceof DateTime) {
    echo 'Yes';
} else {
    echo 'No';
}
medium
A. Yes
B. No
C. Error
D. Nothing

Solution

  1. Step 1: Understand object creation

    $a is created as a new instance of the DateTime class.
  2. Step 2: Check instanceof condition

    The condition $a instanceof DateTime is true because $a is exactly a DateTime object.
  3. Final Answer:

    Yes -> Option A
  4. Quick Check:

    Object is DateTime = Yes [OK]
Hint: If object matches class, instanceof returns true [OK]
Common Mistakes:
  • Assuming instanceof returns false for exact class
  • Expecting syntax error from instanceof
  • Ignoring else branch output
4. Identify the error in this PHP code snippet:
class Animal {}
class Dog extends Animal {}
$dog = new Dog();
if ($dog instanceof 'Animal') {
    echo 'It is an animal';
}
medium
A. Missing semicolon after class definition
B. Incorrect object creation syntax
C. Using quotes around class name in instanceof
D. Using instanceof with a variable instead of object

Solution

  1. Step 1: Check instanceof usage

    The instanceof operator expects a class name without quotes, not a string.
  2. Step 2: Verify other parts

    Classes and object creation are correct; semicolons are present.
  3. Final Answer:

    Using quotes around class name in instanceof -> Option C
  4. Quick Check:

    Class name must be unquoted in instanceof [OK]
Hint: Do not put quotes around class names in instanceof [OK]
Common Mistakes:
  • Putting class names in quotes inside instanceof
  • Confusing instanceof with string comparison
  • Missing semicolons elsewhere (not in this code)
5. Given the classes below, what will be the output?
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);
hard
A. Vehicle
B. Unknown
C. Car
D. Error

Solution

  1. Step 1: Analyze object type

    $myBike is an instance of Bike, which extends Vehicle.
  2. Step 2: Follow function logic

    First condition checks if $obj is Car - false. Second checks if $obj is Vehicle - true because Bike is subclass of Vehicle.
  3. Final Answer:

    Vehicle -> Option A
  4. Quick Check:

    Bike is a Vehicle, not Car = Vehicle [OK]
Hint: Check subclass before superclass in instanceof chains [OK]
Common Mistakes:
  • Expecting 'Car' for Bike object
  • Ignoring subclass relationship in instanceof
  • Assuming instanceof only matches exact class
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard