Back to Top

Inheritance in object-oriented PHP

Inheritance in PHP

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.

Inheritance in object-oriented PHP

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.

    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.

    How many types of Inheritance PHP support?

    PHP supports two types of inheritance.

    1. Single Inheritance: A class can be directly derived only from one superclass.
    2. Multilevel 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.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

How to upload image in CodeIgniter?

Posted on 11 years ago

Bhumi

How to use SQLite Database in PhoneGap?

Posted on 10 years ago

Bhumi