The instanceof Operator
Test whether an object is an instance of a class, subclass, or interface — the backbone of type-safe branching.
instanceof answers "is this object one of these?" It returns true for the exact class, any parent class, and any implemented interface. That makes it the natural tool for handling a mixed bag of objects by their capabilities rather than their concrete type.
Easy example
<?php
interface Animal {}
class Dog implements Animal {}
$d = new Dog();
var_dump($d instanceof Dog); // true
var_dump($d instanceof Animal); // true (interface)
var_dump($d instanceof Iterator); // falseSince PHP 8 you can test against a class name held in a variable too: $obj instanceof $className.
Example
When to use it
- Type-check an event object before calling event-specific methods in a generic event dispatcher.
- Guard a polymorphic rendering function by checking instanceof the expected interface before casting.
- Build a type-safe collection that validates inserted items with instanceof before adding them.
More examples
Basic instanceof check
instanceof tests whether an object satisfies a class or interface contract, enabling safe polymorphic dispatch.
<?php
interface Notifiable {}
class EmailAlert implements Notifiable {}
class SmsAlert {}
function dispatch(object $alert): void {
if ($alert instanceof Notifiable) {
echo get_class($alert) . ' dispatched';
} else {
echo 'Not notifiable';
}
}
dispatch(new EmailAlert()); // EmailAlert dispatched
dispatch(new SmsAlert()); // Not notifiableinstanceof with inheritance
instanceof is true for the class itself and all its ancestors, so it works correctly throughout a class hierarchy.
<?php
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
$pets = [new Dog(), new Cat(), new Dog()];
$dogCount = count(array_filter($pets, fn($p) => $p instanceof Dog));
echo "Dogs: $dogCount"; // Dogs: 2Type-narrowing with instanceof
After an instanceof guard, PHP knows the concrete type, unlocking access to Circle-only methods without a cast.
<?php
interface Shape {
public function area(): float;
}
class Circle implements Shape {
public function __construct(public float $radius) {}
public function area(): float { return M_PI * $this->radius ** 2; }
public function circumference(): float { return 2 * M_PI * $this->radius; }
}
class Square implements Shape {
public function __construct(public float $side) {}
public function area(): float { return $this->side ** 2; }
}
function describe(Shape $s): string {
$base = 'Area: ' . round($s->area(), 2);
if ($s instanceof Circle) {
$base .= ', Circ: ' . round($s->circumference(), 2);
}
return $base;
}
echo describe(new Circle(5));
Discussion