Using Traits in Php To achieve Multiple Inheritance

using traits in php to achieve multiple inheritance#

As we know that php do not support multiple inheritance, if you are new to the work of OOPs programming language please get some knowledge about that.

multiple inheritance means accessing properties from multiple base class, but we cannot extend multiple class, only one calls is allowed to extend

so for that there is traits , traits is like a class but we cannot create objects of traits but we can create properties and methods in that

What happens when we are using traits in any class? It simply copy paste the code written in traits to class which class is using that trait.

for creating traits their is a keyword trait for example.

trait TraitName {
    public function setAddress(){
        // logic for this method
    }
}

and then we can use the above trait in class using use keyword

class Home {
    use TraitName;

    public function updateUser(){

        $this->setAddress();
    }

}

we can access the trait method using $this->method_name it is like traits function are class’s inbuilt function

we can use multiple traits in same class like below

class Home {
    use Trait1;
    use Trait2;
    use Trait3;
    .
    .
}

suppose your two traits have the same method name then we can either create alias for that second method name at time of using that trait or we can use instead of keyword like below.

trait TraitOne {
    public function sayHello(){

    }
}
trait TraitTwo {
    public function sayHello(){

    }
}

class UseTrait {
    use TraitOne { sayHello as hello1;}
    use TraitTwo { sayHello as hello2;}
        
}

class UseAnotherWay {
    use TraitOne, TraitTwo { TraitOne::sayHello insteadof TraitTwo;}

    public function hello() {
        $this->sayHello(); // this will use TraitOne's sayHello()
    }
}

comments powered by Disqus