Handling Conflicts in Traits in PHP

 <?php

//When multiple trait have same named method then we can call both methods as shown below :
trait one
{
    public function test()
    {
        echo "TEST method from one trait.";
    }
}
trait two
{
    public function test()
    {
        echo "TEST method from two trait.";
    }
}
class abc
{
    use one, two {
        // one::test insteadof two;    //Here test() method in trait one will call
        // two::test insteadof one;    //Here test() method in trait two will call

        //Here below First of all, trait "two" method will call and then trait "one" method will call
        two::test insteadof one;
        one::test as OneTest;

        //Here below First of all, trait "one" method will call and then trait "two" method will call
        // one::test insteadof two;
        // two::test as TwoTest;
    }
}
$obj = new abc();
$obj->test();
echo "<br><br>";
$obj->OneTest();
// $obj->TwoTest();
echo "<br><br><br><br><br>";


//Example 2 :
trait Men
{
    public function walk()
    {
        echo "Men walk usually as its personality and walks slowly as compared to Animal and Human runs slowly as compared to Animal";
    }
}
trait Dog
{
    public function walk()
    {
        echo "Dog walk usually as its personality and walks fastly as compared to Human and Animal runs faster as compared to Human";
    }
}
class StyleOfWalk
{
    use Men, Dog {
        //Here below First of all, trait "Men" method will call and then trait "Dog" method will call
        Men::walk insteadof Dog;
        Dog::walk as MenWalk;

        //Here below First of all, trait "Dog" method will call and then trait "Men" method will call
        // Dog::walk insteadof Men;
        // Men::walk as DogWalk;
    }
}
$obj = new StyleOfWalk();
$obj->walk();
echo "<br><br>";
$obj->MenWalk();
// $obj->DogWalk();



Comments

Popular posts from this blog

GROUP BY Clause and HAVING Clause in PHP

Method Overriding in Traits in PHP

Mysqli database Connection and Display Table Data from Database