0
0
PHPprogramming~5 mins

Instanceof operator in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the instanceof operator do in PHP?
It checks if an object is an instance of a specific class or implements a specific interface.
Click to reveal answer
beginner
How do you use instanceof to check if $obj is an instance of class Car?
Use <code>$obj instanceof Car</code>. It returns <code>true</code> if <code>$obj</code> is a Car or subclass of Car, otherwise <code>false</code>.
Click to reveal answer
intermediate
Can instanceof check if an object implements an interface?
Yes. It returns true if the object implements the interface, otherwise false.
Click to reveal answer
beginner
What will instanceof return if the variable is not an object?
It returns false because instanceof only works with objects.
Click to reveal answer
intermediate
Explain why instanceof is useful in PHP programming.
It helps to safely check an object's type before calling methods or accessing properties, preventing errors.
Click to reveal answer
What does $obj instanceof ClassName return if $obj is an instance of a subclass of ClassName?
Afalse
Btrue
Cnull
DThrows an error
Which of the following is true about instanceof in PHP?
AIt can check if an object implements an interface.
BIt can check if a variable is an integer.
CIt can check if a string contains a class name.
DIt can create a new instance of a class.
What will instanceof return if the variable is null?
Afalse
BThrows an error
Cnull
Dtrue
If $obj instanceof InterfaceName returns true, what does it mean?
A$obj is a subclass of InterfaceName.
B$obj is a string containing InterfaceName.
C$obj is an instance of a class that implements InterfaceName.
D$obj is an array.
Which of these is a correct use of instanceof?
Aif (MyClass instanceof $obj) { /* code */ }
Bif (instanceof $obj MyClass) { /* code */ }
Cif ($obj instanceof 'MyClass') { /* code */ }
Dif ($obj instanceof MyClass) { /* code */ }
Describe how the instanceof operator works in PHP and give an example.
Think about checking an object's type before using it.
You got /4 concepts.
    Explain why using instanceof can help prevent errors in PHP programs.
    Consider what happens if you call a method on a variable that is not an object.
    You got /4 concepts.