PHP instanceof: Check if Object Belongs to a Class
This article explains how to use the PHP instanceof
operator to determine whether a specific object belongs to a given
class, inherits from a parent class, or implements a specific interface.
You will learn the basic syntax, see clear code examples demonstrating
inheritance and interfaces, and understand how the operator behaves with
non-object types.
The instanceof operator is a built-in PHP feature used
for type comparison. It returns a boolean value: true if
the object matches the specified class or interface, and
false otherwise.
Basic Syntax
To use the operator, place the object variable on the left side, the operator in the middle, and the class name on the right side.
$result = $object instanceof ClassName;Checking Class Membership
Here is a simple example checking if an object is an instance of a specific class:
class User {
// Class properties and methods
}
$user = new User();
if ($user instanceof User) {
echo "The object is a User.";
}Checking Inheritance (Subclasses)
The instanceof operator also detects if an object
belongs to a class that inherits from a parent class.
class Animal {}
class Dog extends Animal {}
$dog = new Dog();
var_dump($dog instanceof Dog); // bool(true)
var_dump($dog instanceof Animal); // bool(true)In this example, $dog is an instance of both
Dog and its parent class Animal.
Checking Interfaces
You can also use instanceof to verify if an object’s
class implements a specific interface. This is highly useful for
polymorphism and dependency injection.
interface Loggable {
public function log();
}
class FileLogger implements Loggable {
public function log() {
// Logging logic
}
}
$logger = new FileLogger();
if ($logger instanceof Loggable) {
echo "The object can perform logging operations.";
}Handling Non-Object Types
If the variable being tested is not an object,
instanceof will safely return false instead of
throwing an error.
$notAnObject = "I am a string";
var_dump($notAnObject instanceof User); // bool(false)