What is PHP get_parent_class() Function?
If you want to know the immediate parent for a class or an object, use PHP get_parent_class() function.
Syntax:
get_parent_class(class_or_object)
Parameters:
The Function has 1 parameter which is required-
object_or_class (Required): It specifies an object (check example 1) or a string which represent a class name (check example 2).
Return Values:
The function returns-
- Name of the parent class as a string, on success.
- FALSE, if the class or object has no parent or the class doesn’t exist. Check example 3.
Examples:
Example 1:
<?php
class Human {}
class Male extends Human {
public $finger = 20;
}
$objMale = new Male();
echo "Parent class of the object '\$objMale' is: " . get_parent_class($objMale);
?>
Output:
Parent class of the object '$objMale' is: Human
Example 2:
<?php
class Human {}
class Male2 extends Human {
public $finger = 20;
}
echo "Parent class of the class 'Male' is: " . get_parent_class('Male');
?>
Output:
Parent class of the object class 'Male' is: Human
Example 3:
<?php
class Male {}
echo "Parent class of the class 'Bird' is: "; var_dump(get_parent_class('Male'));
?
Output:
Parent class of the class 'Bird' is: bool(false)
Notes on get_parent_class() Function:
- You can class this function inside and outside of the child class using the class name parameter. Inside the class you can call this using $this. See the example below-
<?php
class Human {}
class Male extends Human {
function __construct(){
echo "Clild class 'Male's parent class is: " . get_parent_class('Male') . "<br />";
}
}
class Female extends Human {
function __construct(){
echo "Clild class 'Female3's parent class is: " . get_parent_class($this);
}
}
new Male3();
new Female3();
?>
Output:
Clild class 'Male's parent class is: Human
Clild class 'Female's parent class is: Human
PHP Version Support:
PHP 4, PHP 5, PHP 7, PHP 8
Summary: PHP get_parent_class() Function
get_parent_class() is a class/object type function in PHP. It is a useful function to know the hierarchy of an class.