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); // false

Since PHP 8 you can test against a class name held in a variable too: $obj instanceof $className.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

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.

Example · php
<?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 notifiable

instanceof with inheritance

instanceof is true for the class itself and all its ancestors, so it works correctly throughout a class hierarchy.

Example · php
<?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: 2

Type-narrowing with instanceof

After an instanceof guard, PHP knows the concrete type, unlocking access to Circle-only methods without a cast.

Example · php
<?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

  • Be the first to comment on this lesson.