Tutorial Image

PHP OOP Inheritance

When one class shares code from another class, then this process is known as inheritance.

In other words, when a class is derived from another class then this process is known as inheritance. The derived class is known as child class or subclass or derived class and the other class from which the child derived is the parent class or superclass.

Followings are the features of inheritance:

  • Inheritance provides flexibility to write code in the parent class and use it in both parent and child classes.
  • The child class inherits all the public and protected properties and methods from the parent class. Although, it has its own properties and methods.
  • The child class uses the extends keyword when it inherits the parent class.

General Syntax

Try it now

Source Code

Try it now

Let us understand the above example.

We inherited the Mango class from the Fruit class

The child class displayMessage() method access the property $name & $color of parent class.

Using Protected Access Modifier

Please keep in mind that the protected access modifier is visible in the defined class as well as inside the inheritance class.

By declaring a property and method to protect, you can not access outside of the child and parent class. Let us understand it with the help of an example.

Source Code

Try it now

PHP - Overriding Inherited Methods

Inherited methods can be overridden inside the child class by redefining the same method.

Let us see it with the help of an example.

Source Code

Try it now

PHP - The final Keyword

The final keyword is used for :

  • To prevent class inheritance
  • To prevent method overriding

General Syntax

Try it now

Source Code

Try it now