Consider the following PHP code snippet. What will it output?
<?php class Animal {} class Dog extends Animal {} $dog = new Dog(); if ($dog instanceof Animal) { echo 'Yes'; } else { echo 'No'; } ?>
Remember that instanceof checks if an object is an instance of a class or its subclass.
The object $dog is an instance of Dog, which extends Animal. So $dog instanceof Animal returns true, printing 'Yes'.
Given this PHP code, what will be printed?
<?php interface Flyer {} class Bird implements Flyer {} $bird = new Bird(); if ($bird instanceof Flyer) { echo 'Can fly'; } else { echo 'Cannot fly'; } ?>
Check if instanceof works with interfaces as well as classes.
The object $bird implements the interface Flyer, so $bird instanceof Flyer returns true and prints 'Can fly'.
Analyze this PHP code and select the correct output or error message.
<?php class Vehicle {} $car = new Vehicle(); if ($car instanceof NonExistentClass) { echo 'Yes'; } else { echo 'No'; } ?>
What happens if you use instanceof with a class name that does not exist?
Using instanceof with a class name that is not defined causes a fatal error in PHP because the class does not exist.
What will this PHP code print?
<?php class Person {} $person = null; if ($person instanceof Person) { echo 'Is a person'; } else { echo 'Not a person'; } ?>
Check how instanceof behaves when the variable is null.
When the variable is null, instanceof returns false without error, so it prints 'Not a person'.
Select the only true statement about the instanceof operator in PHP.
Think about what happens if you use instanceof with a class name that PHP does not know.
Using instanceof with a class or interface name that does not exist causes a fatal error in PHP. It cannot check unknown types. It returns false for null variables and cannot check primitive types.