Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

Multiple inheritance in PHP and Traits utilization?

user-image
Question added by shahbaz khan , Senior PHP Web Developer , IBM Systems (US)
Date Posted: 2017/01/03
Manoj Kumar Garwa
by Manoj Kumar Garwa , Sr Software Engineer , HireRight Background Verification LLP

First question that comes in mind that why do we need Multiple Inheritance. so answer is for an example you are working within a team of n. your team lead created few functions or many functions within different classes i.e. we can call it for now Component. Now he/she wants his/her team member to use these functions because you will use them on various places. so for time being there are various ways to do so as we all know. but to make multiple inheritance possible we need to use all classes that team lead created earlier but oops we can't use it as PHP doesn't allow it.

 

Multiple Inheritance is not possible in PHP but after php V5.4 we can make it possible via an indirect way same as interface but with a good feature that no need to override all function. Unike interface we can declare and define function in Traits. Here is an example of PHP Traits [Ref: php.net]:

 

<?php

trait Hello {    

    function sayHello() {        

        echo 'Hello ';   

     }

}

trait World {

    public function sayWorld() {

        echo 'World';  

    }

}

class MyHelloWorld {   

    use Hello, World;

    public function sayExclamationMark() {

        echo '!';    

    }

}

$o = new MyHelloWorld();

$o->sayHello();

$o->sayWorld();

$o->sayExclamationMark();

?>

 

So same as this example we can define numbers of traits containing multiple functions and use the using USE keyword.

Now our team lead can start to write TRAITS instead of CLASSES. and his/her team member can use it wherever they want.

for more information on Traits read this: php5 traits

More Questions Like This