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.
if ($shape instanceof Circle) { echo $shape->radius; }
Try it
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.
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
$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 Bworks becauseinstanceofbinds 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
useimports, 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 ofGenerator. - Type checks for scalars use
is_int(),is_string()and friends, notinstanceof. get_class()is stricter.$x instanceof Parentis true for subclasses, whileget_class($x) === Parent::classis only true for the exact class.- Interfaces such as
Countablecan be tested the same way, which is how libraries accept "anything countable".