Open In App

PHP is_subclass_of() Function

Last Updated : 28 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 GeeksforGeek {
    var $color = "Red";
}
class Articles extends GeeksforGeek {
    var $user = 'Test';
}
  
$ob = new GeeksforGeek();
$article = new Articles();
  
if (is_subclass_of($article, 'GeeksforGeek')) {
    echo "Yes, Article is subclass of GeeksforGeek";
}
else {
    echo "No, Articles is not subclass of GeeksforGeek";
}
?>


Output:

Yes, Article is subclass of GeeksforGeek                                              

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

PHP




<?php
interface GeeksforGeek {
    public function hello();
}
class Articles implements GeeksforGeek {
    function hello() {
        echo "Hey GeeksforGeeks";
    }
}
  
$ob = new Articles;
  
if (is_subclass_of($ob, 'GeeksforGeek')) {
    echo "Yes, Articles implements GeeksforGeek interface\n";
}
else {
    echo "No, Articles do not implement GeeksforGeek 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 GeeksforGeek interface
No, Articles do not implement Network interface 

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads