PHP Inheritance

PHP Inheritance


Inheritance : Inheritance provides you with many benefits that make PHP programming a lot more convenient. One such benefit is code reusability. Reusability allows you to generate clean code and the replication of code gets reduced to almost zero. Reusing existing codes serves various advantages. It saves time, cost, effort, and increases a program’s reliability.

In Object oriented programming Inhertiance is a relationship between two or more classes where derived class inherits property of pre existing base class

Base class :it is the class whose properties are inherited by another class.It is also called super class and parent class.

Derived class:it is the class that inherit properties form base class.it is also called sub class and child class.

An inherited class is defined by using the extends keyword.

We can see simple example of inherit base class given below :

The Strawberry class is inherited from the Fruit class.

This means that the Strawberry class can use the public $name and $color properties as well as the public __construct() and intro() methods from the Fruit class because of inheritance.

The Strawberry class also has its own method: message().

Ouput :Am I a fruit or a berry? The fruit is Strawberry and the color is red.

Another Example is Inheritance with Protected Access modifier

Let's understand this with example :

In this example protected method (intro()) from outside the class, we will receive an error. public methods will work fine!

Output :