Multiple Inheritance in PHP

Introduction

Multiple inheritance allows a class to have more than one base class.

An example of multiple inheritance

Many of the object oriented programming languages, like C#, Java and PHP do not support multiple inheritance. To allow this feature, you can use interfaces in PHP or you can use "Traits" in PHP instead of classes for implementing multiple inheritance in PHP. Therefore we are concerned about what "Traits" are. So the answer is that "A Trait is similar to an abstract class, that cannot be instantiated on its own and a Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in various class hierarchies".

In the following example, we are using "trait" to enaible a multiple inheritance feature. The "use" is for using "trait" functionality. The class CompName shows how to use "trait".

<?php

class BaseClass

{

public function Hello()

echo 'Mcn '

trait OtherCls

public function Hello()

parent::Hello(); 

echo 'Solution!'

 

class CompName extends BaseClass

    use OtherCls;  

 

$obj = new CompName(); 

$obj->Hello();
?>

OutPut:

multiple-inheritance-in-php.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all