PHP instanceof Keyword
Example
Check whether an object belongs to a specific class:
<?php
class MyClass {}
class AnotherClass extends MyClass{}
$obj = new AnotherClass();
if($obj instanceof AnotherClass) {
echo "The object is AnotherClass";
}
// The object is also an instance of the class it is derived from
if($obj instanceof MyClass) {
echo "The object is MyClass<br>";
}
?>
Try it Yourself »
class MyClass {}
class AnotherClass extends MyClass{}
$obj = new AnotherClass();
if($obj instanceof AnotherClass) {
echo "The object is AnotherClass";
}
// The object is also an instance of the class it is derived from
if($obj instanceof MyClass) {
echo "The object is MyClass<br>";
}
?>
Definition and Usage
The instanceof keyword is used to check if an object belongs to a class. The
comparison returns true if the object is an instance of the class, it returns false if it is not.
Related Pages
Read more about object and classes in our PHP OOP Tutorial.
❮ PHP Keywords