The instanceof Operator

The instanceof operator checks if an object is an instance of the specified class or its descendant. It accepts the object as the first parameter and the class name for checking as the second. Returns true if the object belongs to the class or false otherwise.

Syntax

php$object instanceof ClassName;

Example

Let's check if the object is an instance of the MyClass class:

php<?php
  class MyClass {}
  $obj = new MyClass();
  var_dump($obj instanceof MyClass);
?>

Code execution result:

phptrue

Example

Let's check class inheritance:

php<?php
  class ParentClass {}
  class ChildClass extends ParentClass {}
  
  $child = new ChildClass();
  var_dump($child instanceof ParentClass);
?>

Code execution result:

phptrue

Example

Let's check that the object is not an instance of the class:

php<?php
  class A {}
  class B {}
  
  $a = new A();
  var_dump($a instanceof B);
?>

Code execution result:

phpfalse

See Also

  • the get_class function,
    which returns the name of the object's class
  • the is_a function,
    which checks if an object belongs to a class