What is the get_parent_class() method in PHP?
Overview
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.
What is 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.
Syntax
get_parent_class($object_or_class)
Parameter
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.
Return value
The function returns the name of the parent class.
Code
In the code snippet below, the following is being done:
-
A parent class named
mainClassis created. -
Two child classes named
subClass1andsubClass2are created. They are made the children ofmainClassthrough theextendskeyword. -
The
get_parent_class()function was used insubClass1andsubClass2, 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();?>