PHP get_parent_class() Tutorial 🎯

beginner
5 min

PHP get_parent_class() Tutorial 🎯

Welcome to CodeYourCraft! Today, we're diving into the PHP function get_parent_class(). This function is a powerful tool for understanding the inheritance hierarchy in Object-Oriented Programming (OOP) in PHP. Let's get started!

Understanding the get_parent_class() Function πŸ“

The get_parent_class() function in PHP returns the name of the parent class of an object. This function is particularly useful when working with inheritance, a fundamental concept in OOP.

Inheritance in PHP πŸ’‘

Inheritance is a mechanism where one class acquires the properties and methods of another. The class that inherits is called the subclass or derived class, while the class being inherited from is called the superclass or base class.

Using get_parent_class() πŸ“

To use get_parent_class(), you first need to create a parent class and a child class that inherits from the parent. Let's create an example:

php
// Parent Class class Animal { public function makeNoise() { echo "The animal makes a noise.\n"; } } // Child Class inheriting from Animal class Dog extends Animal { public function bark() { echo "Woof woof!\n"; } }

In the above example, Dog is a child class that inherits from the Animal class. Now, let's see how to use get_parent_class():

php
$dog = new Dog(); $parentClass = get_parent_class($dog); echo "Parent class of Dog is: " . $parentClass[0] . "\n";

In the above code, we create an instance of the Dog class, then use get_parent_class() to find the parent class of Dog. The output will be:

Parent class of Dog is: Animal

Advanced Usage πŸ’‘

get_parent_class() can also be used with interfaces in PHP. Remember, a class can implement multiple interfaces but can have only one parent class.

php
// Interface interface Flyable { public function fly(); } // Parent Class class Bird implements Flyable { public function fly() { echo "The bird is flying.\n"; } } // Child Class inheriting from Bird and implementing Flyable class Eagle extends Bird { // No need to re-declare the fly() method, as it's inherited } $eagle = new Eagle(); $parentClass = get_parent_class($eagle); echo "Parent class of Eagle is: " . $parentClass[0] . "\n";

In this example, Eagle is a child class that both inherits from Bird and implements the Flyable interface. The output will be:

Parent class of Eagle is: Bird

Quiz πŸ“

By now, you should have a good understanding of the get_parent_class() function in PHP. Happy coding! πŸš€