PHP is_subclass_of() Function
The PHP is_subclass_of() function is used to check if the given object_or_class has the specified class as one of its parents or implements it.
Syntax
is_subclass_of(object_or_class, class, allow_string)
Parameters
object_or_class |
Required. Specify a class name or an object instance. No error is generated if the class does not exist. |
class |
Required. Specify the class name. |
allow_string |
Optional. If set to false, string class name as object_or_class is not allowed. This also prevents from calling autoloader if the class does not exist. |
Return Value
Returns true if the object object_or_class, belongs to a class which is a subclass of class, false otherwise.
Example: is_subclass_of() example
The example below shows the usage of is_subclass_of() function.
<?php //defining a class class WidgetFactory { //codes } //defining a child class class WidgetFactory_Child extends WidgetFactory { //codes } //creating new objects $WF = new WidgetFactory(); $WFC = new WidgetFactory_Child(); if (is_subclass_of($WFC, 'WidgetFactory')) { echo "Yes, \$WFC is a subclass of WidgetFactory\n"; } else { echo "No, \$WFC is not a subclass of WidgetFactory\n"; } if (is_subclass_of($WF, 'WidgetFactory')) { echo "Yes, \$WF is a subclass of WidgetFactory\n"; } else { echo "No, \$WF is not a subclass of WidgetFactory\n"; } if (is_subclass_of('WidgetFactory_Child', 'WidgetFactory')) { echo "Yes, WidgetFactory_Child is a subclass of WidgetFactory\n"; } else { echo "No, WidgetFactory_Child is not a subclass of WidgetFactory\n"; } ?>
The output of the above code will be:
Yes, $WFC is a subclass of WidgetFactory No, $WF is not a subclass of WidgetFactory Yes, WidgetFactory_Child is a subclass of WidgetFactory
Example: is_subclass_of() using interface example
Consider the example below where this function is used with interface.
<?php //defining the Interface interface MyInterface { public function MyFunction(); } //defining the class implementation of the interface class MyClass implements MyInterface { public function MyFunction() { //codes } } //creating new object $myObj = new MyClass(); //checking using the object instance of the class if (is_subclass_of($myObj, 'MyInterface')) { echo "Yes, \$myObj is a subclass of MyInterface\n"; } else { echo "No, \$myObj is not a subclass of MyInterface\n"; } //checking using a string of the class name if (is_subclass_of('MyClass', 'MyInterface')) { echo "Yes, MyClass is a subclass of MyInterface\n"; } else { echo "No, MyClass is not a subclass of MyInterface\n"; } ?>
The output of the above code will be:
Yes, $myObj is a subclass of MyInterface Yes, MyClass is a subclass of MyInterface
❮ PHP Classes/Objects Reference