Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Operators

The PHP instanceof operator

Reference for the PHP instanceof operator: test whether an object belongs to a class, subclass, interface or Closure, with dynamic class names and pitfalls.

instanceof tests whether a value is an object of a given class, of a subclass of it, or of a class that implements a given interface. It returns true or false and never throws, even if the left side is not an object or the class does not exist.

Use it when behavior depends on the concrete kind of object you received, for example in a catch-like dispatch or before calling a method that only some implementations have. Prefer polymorphism when you can; instanceof chains are often a sign that a method belongs on the interface.

PHP
if ($shape instanceof Circle) {
    echo $shape->radius;
}

Try it

PHP Classes, parents and interfaces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Dynamic class names and negation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
$object instanceof ClassName
$object instanceof $classNameString
$object instanceof $otherObject
Right side Meaning
Class or interface name True if the object is an instance of it, of a subclass, or implements it
String variable The string holds a class name (resolved at run time)
Object variable True if the left object has the same class (or a subclass) as the right object

Result: bool. A non-object on the left gives false. An unknown class name gives false and does not trigger autoloading.

Usage notes

  • No quotes around a literal name. $x instanceof "Foo" is a syntax error; use a variable or a bare name.
  • Negate with parentheses. !$a instanceof B works because instanceof binds tighter than !, but !($a instanceof B) reads better. See operator precedence.
  • Names follow namespace rules. An unqualified name is resolved against the current namespace and use imports, so write the full or imported name. See namespace and use.
  • Closures are instances of Closure, enum cases are instances of their enum, and generators are instances of Generator.
  • Type checks for scalars use is_int(), is_string() and friends, not instanceof.
  • get_class() is stricter. $x instanceof Parent is true for subclasses, while get_class($x) === Parent::class is only true for the exact class.
  • Interfaces such as Countable can be tested the same way, which is how libraries accept "anything countable".