PHP is_subclass_of() Function

The is_subclass_of() function is an inbuilt function in PHP that checks whether the object inherits from or implements the specified class.

Syntax:

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

Parameters: This function accept three parameters that are described below:

  • $object or class: Either a class name or an object instance can be specified, and if the specified class does not exist, no error will be generated.
  • $class: This parameter specifies the class name in a string format.
  • $allow_string: The string class name or object can’t be used if this parameter is set to false. If the class doesn’t exist, then this parameter prevents from calling the autoloader.

Return Value: If the object or class belongs to the parent class, this function will return “true”; otherwise, it will return “false”.

Example 1: This example demonstrates the PHP is_subclass_of() function.

PHP




<?php
class BeginnerforGeek {
    var $color = "Red";
}
class Articles extends BeginnerforGeek {
    var $user = 'Test';
}
  
$ob = new BeginnerforGeek();
$article = new Articles();
  
if (is_subclass_of($article, 'BeginnerforGeek')) {
    echo "Yes, Article is subclass of BeginnerforGeek";
}
else {
    echo "No, Articles is not subclass of BeginnerforGeek";
}
?>


Output:

Yes, Article is subclass of BeginnerforGeek                                              

Example 2: The following code demonstrates another example of the PHP is_subclass_of() method.

PHP




<?php
interface BeginnerforGeek {
    public function hello();
}
class Articles implements BeginnerforGeek {
    function hello() {
        echo "Hey w3wiki";
    }
}
  
$ob = new Articles;
  
if (is_subclass_of($ob, 'BeginnerforGeek')) {
    echo "Yes, Articles implements BeginnerforGeek interface\n";
}
else {
    echo "No, Articles do not implement BeginnerforGeek interface\n";
}
  
if (is_subclass_of($ob, 'Network')) {
    echo "Yes, Articles implements Network interface";
}
else {
    echo "No, Articles do not implement Network interface";
}
?>


Output:

Yes, Articles is implement BeginnerforGeek interface
No, Articles do not implement Network interface 

Reference: https://www.php.net/manual/en/function.is-subclass-of.php