Search code examples
phptraits

Multiple traits uses same base trait at the same time


Okay say the following straits are given:

trait Base
{
    public function doSomething()
    {
        // Do fancy stuff needed in other traits
    }
}

trait A
{
    use Base;

    public function foo()
    {
        // Do something
    }
}


trait B
{
    use Base;

    public function bar()
    {
        // Do something else
    }
}

and I like to implement a class now which uses both traits A and B:

class MyClass
{
    use A, B;
}

PHP tells me it can't redefine function doSomething(). What's the reason PHP is not able to detect that A and B share one and the same trait and don't copy it twice into MyClass (is it a bug or a feature preventing me from writing unclean code)?

Is there a better solution for my problem then this workaround with which I ended up:

trait Base
{
    public function doSomething()
    {
        // Do fancy stuff needed in other traits
    }
}

trait A
{
    abstract function doSomething();

    public function foo()
    {
        // Do something
    }
}


trait B
{
    abstract function doSomething();

    public function bar()
    {
        // Do something else
    }
}

And then my class:

class MyClass
{
    use Base, A, B;
}

Solution

  • You can resolve this conflict with "insteadof" like this:

    class MyClass
    {
        use A, B {
            A::doSomething insteadof B;
        }
    } 
    

    EDIT For more traits resolving conflicts can look like this:

    class MyClass
    {
        use A, B, C, D {
            A::doSomething insteadof B, C, D;
        }
    }