326 of 410 menu

The is_subclass_of Function

The is_subclass_of function checks whether an object or class belongs to the descendants of the specified class or whether it implements the specified interface. The first parameter accepts an object or class name, the second - the name of the parent class or interface. The third optional parameter determines whether class autoloading should be taken into account.

Syntax

is_subclass_of(mixed $object_or_class, string $class, bool $allow_string = true): bool

Example

Let's check the inheritance of simple classes:

<?php class ParentClass {} class ChildClass extends ParentClass {} $res = is_subclass_of('ChildClass', 'ParentClass'); var_dump($res); ?>

Code execution result:

true

Example

Let's check the interface implementation:

<?php interface MyInterface {} class MyClass implements MyInterface {} $res = is_subclass_of('MyClass', 'MyInterface'); var_dump($res); ?>

Code execution result:

true

Example

Checking with an object instead of a class name:

<?php class Animal {} class Dog extends Animal {} $dog = new Dog(); $res = is_subclass_of($dog, 'Animal'); var_dump($res); ?>

Code execution result:

true

Example

Checking the case when a class is not a descendant:

<?php class A {} class B {} $res = is_subclass_of('B', 'A'); var_dump($res); ?>

Code execution result:

false

See Also

  • the is_a function,
    which checks class membership
  • the class_parents function,
    which returns all parents
  • the get_parent_class function,
    which returns the parent class
  • the instanceof function,
    the instance check operator
byenru