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.
<?php
class Parent_1{
public $a;
public function first($a){
$this->a = $a;
}
}
trait Parent_2{
public $b;
public function second($b){
$this->b = $b;
}
}
class Child extends Parent_1{
use Parent_2;
private $sum;
public function sum(){
$this->sum = $this->a + $this->b;
echo "Sum of two variables -> ".$this->sum;
}
}
$object = new Child;
$object->first(10);
$object->second(20);
$object->sum();
?>
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 is created having $a variable |
2. |
|
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. |
|
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 |
4. |
|
Method sum is using the variables of both parent classes to calculate the addition. |
5. |
|
Object is created only for child class. |
6. |
|
Parent_1, Parent_2 and Child methods are accessed with |
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.