Classes can extend other classes in PHP. This entails that these new classes will inherit properties and methods from the parent or base class from which they extend. If you wish to grab the base class from which a child class inherits from somewhere in your code, you can use the get_parent_class()
function.
get_parent_class()
It is a method in PHP which returns the name of the parent class from which the indicated class or object inherits from or extends.
get_parent_class($object_or_class)
The function takes a single parameter, object_or_class
, which is the string name of the object or class whose parent class is being checked for.
The function returns the name of the parent class.
In the code snippet below, the following is being done:
A parent class named mainClass
is created.
Two child classes named subClass1
and subClass2
are created. They are made the children of mainClass
through the extends
keyword.
The get_parent_class()
function was used in subClass1
and subClass2
, which returns the name of the parent class (mainClass
) of both these child classes.
<?php// main classclass mainClass {function __construct(){// implements some logic}}// child class 1class subClass1 extends mainClass {function __construct(){echo "I'm " , get_parent_class($this) , "'s child\n";}}// child class 2class subClass2 extends mainClass {function __construct(){echo "I'm " , get_parent_class('subClass2') , "'s child too\n";}}// objects of the above classes.$freshObj = new subClass1();$newObj = new subClass2();?>