You can use the instanceof operator, to check if an object is an instance of :
- A class
- Or a child class of that class
- Or an instance of a class that implements an interface
Which means that it cannot be used to detect if your object is an instance of a specific class — as it will say “yes” if your object is an instance of a child-class of that class.
For instance, this portion of code :
class ClassA {}
class ClassB extends ClassA {}
$a = new ClassB();
if ($a instanceof ClassA) {
echo '$a is an instanceof ClassA<br />';
}
if ($a instanceof ClassB) {
echo '$a is an instanceof ClassB<br />';
}
Will get you this output :
$a is an instanceof ClassA
$a is an instanceof ClassB
$a, in a way, is an instance of ClassA, as ClassB is a child-class of ClassA.
And, of course, $a is also an instance of ClassB — see the line where it’s instanciated.