0
0
PHPprogramming~20 mins

Instanceof operator in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Instanceof Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this PHP code using instanceof?

Consider the following PHP code snippet. What will it output?

PHP
<?php
class Animal {}
class Dog extends Animal {}
$dog = new Dog();
if ($dog instanceof Animal) {
    echo 'Yes';
} else {
    echo 'No';
}
?>
ANo
BYes
CFatal error
Dnull
Attempts:
2 left
💡 Hint

Remember that instanceof checks if an object is an instance of a class or its subclass.

Predict Output
intermediate
2:00remaining
What does this code output when checking interface with instanceof?

Given this PHP code, what will be printed?

PHP
<?php
interface Flyer {}
class Bird implements Flyer {}
$bird = new Bird();
if ($bird instanceof Flyer) {
    echo 'Can fly';
} else {
    echo 'Cannot fly';
}
?>
ACan fly
BNo output
CFatal error
DCannot fly
Attempts:
2 left
💡 Hint

Check if instanceof works with interfaces as well as classes.

Predict Output
advanced
2:00remaining
What error or output does this code produce?

Analyze this PHP code and select the correct output or error message.

PHP
<?php
class Vehicle {}
$car = new Vehicle();
if ($car instanceof NonExistentClass) {
    echo 'Yes';
} else {
    echo 'No';
}
?>
AYes
BWarning: instanceof expects an object
CFatal error: Class 'NonExistentClass' not found
DNo
Attempts:
2 left
💡 Hint

What happens if you use instanceof with a class name that does not exist?

Predict Output
advanced
2:00remaining
What is the output of this code using instanceof with null?

What will this PHP code print?

PHP
<?php
class Person {}
$person = null;
if ($person instanceof Person) {
    echo 'Is a person';
} else {
    echo 'Not a person';
}
?>
ANot a person
BIs a person
CFatal error
DWarning: instanceof expects an object
Attempts:
2 left
💡 Hint

Check how instanceof behaves when the variable is null.

🧠 Conceptual
expert
2:00remaining
Which statement about the instanceof operator in PHP is TRUE?

Select the only true statement about the instanceof operator in PHP.

Ainstanceof can be used to check if a variable is a primitive type like integer or string.
Binstanceof returns true if the variable is null and the class name matches any class.
Cinstanceof can be used to check if a variable is an instance of a class or interface, even if the class or interface does not exist.
Dinstanceof throws a fatal error if the class or interface name used does not exist in the code.
Attempts:
2 left
💡 Hint

Think about what happens if you use instanceof with a class name that PHP does not know.