In this article, we are going to learn PHP Inheritance. When we talk about PHP Inheritance, the first and the most basic question that comes to our mind is, what is inheritance?
Inheritance means to inherit something from the existing.
Let’s understand the concept of PHP inheritance with some real world example that plays around us. We all know that every child receives a property (like home, land, and car) from his parent as an inheritance.
E.g. Joe IS-A son of Jonathan.
In the above example, the relationship between Jonathan and Joe is parent and child, that indicates whatever the property Jonathan (parent) has, will be automatically available to his child Joe (child) as an inheritance.
Key Points to Remember:
- Inheritance represents IS-A relations ship between two objects.
- PHP reserve keyword extends used to represent inheritance in PHP.
- Single Inheritance: A class can be directly derived only from one superclass.
- Multilevel Inheritance
Now, the question that comes to our mind is, how do we represent this relationship as an inheritance in PHP? Let’s see with below example.
In the below example, we can see that Joe (child) class derived from Jonathan (parent) superclass using extends keywords. The class that derives from super class is known as a subclass.
1 2 3 4 5 6 7 8 | /* Child class */ class Joe extends Jonathan { // By extending parent class // all the property that are declare with //public, protected or default will be available in child } |
How many types of Inheritance PHP support?
PHP supports two types of inheritance.
Does PHP Support Multiple Inheritance?
The answer is very simple, PHP does not support multiple inheritances. But using the Interface we can achieve multiple inheritances in PHP.
Advantages of Inheritance:
The main advantage of inheritance is code re-usability. It simply means that we can use the superclass property and method in derive subclass directly. We do not have to re-invent the wheel again.