Skip to main content
Submitted by manoj on 15 October 2022

We can achieve Multiple Inheritance  by using trait.

What is trait in php?

Sometimes we may want to inherit from more than one class. Since this is not possible in PHP so we can achieve  by traits.

What is a trait?

In PHP, a trait is a way  to inherit  multiple independent classes to a class achieve  Multiple inheritance.

You can inherit trait through the use keyword.

yml Copy

<?php
/*
Multiple Inheritance

*/
trait One {
    
    function index_one(){
        echo " I am class One";
        
    }
    
}

class Two {
    function index_two(){
            echo " I am class Two";
        
    }    
}

/*
Here we have  Actually achieved Multiple Inheritance.

*/

class Three extends Two {
    use One;
    function index_three(){
        
        echo " I am class Three";
        
    }    

}

$Obj = new Three();
echo $Obj->index_three()."<br/>";
echo $Obj->index_two()."<br/>";
echo $Obj->index_one();