Multiple Inheritance in PHP

Pre-requisites: Basic Understanding of Programming Language, MySQL.

In this project,

  • We will create a class and a trait.
  • Traits in PHP are used to implement multiple inheritance. We use ‘trait’ keyword for this.
  • A new class will be inherited from two parent classes created above.
  • This new class will derive all the protected and public members of parent classes along with its new properties and methods.
  • Object of child class will access all the methods of parent classes as well.

Type the following code in a PHP editor and save the file as MultipleInheritance.php in Classes folder of your root directory.

 

Multiple Inheritance in PHP

  

Run MultipleInheritance.php file in your browser to get the following output. URL may look like as follows:

 

Code Explanation of MultipleInheritance.php

1.

class Parent_1{

    public $a;

    public function first($a){

        $this->a = $a;

    }

}

Class Parent_1 is created having $a variable

2.

trait Parent_2{

    public $b;

    public function second($b){

        $this->b = $b;

    }

}

Parent_2 is declared as a trait, although its definition will be similar to the class definition.

 

Syntax to declare a trait:

 

trait trait_name{

}

3.

class Child extends Parent_1{

    use Parent_2;

    private $sum;

}

Child class is extending Parent_1 and using Parent_2 as a trait in order to inherit the properties of both classes.

 

Syntax to use trait:

 

use trait_name;

4.

public function sum(){

        $this->sum = $this->a + $this->b;

        echo "Sum of two variables -> ".$this->sum;

}

Method sum is using the variables of both parent classes to calculate the addition.

5.

$object = new Child;

Object is created only for child class.

6.

$object->first(10);

$object->second(20);

$object->sum();

Parent_1, Parent_2 and Child methods are accessed with $object of Child class.

 

Summary

 

In this project, we have learned to implement multiple inheritance in PHP using traits.

We have declared $a variable in Parent_1 class and $b variable in Parent_2 class which is declared as a trait using trait keyword.

A child is created which is inherited from Parent_1 class using extends keyword and Parent_2 is used as a trait using the following syntax:

use Parent_2;

Sum of $a and $b variable is calculated in Child class and is displayed accordingly.

Methods are accessed using the Child class object i.e. $object.

This is how, multiple inheritance is achieved in PHP.

Help Us to Improve our content

Let's Talk
Go back to Previous Course

© 2021 Lecturely.com. All rights reserved.

Lecturely.com – Imagined by Paras Jairath, Developed by P3 Multisolutions & Powered by Network Bulls.