Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple traits uses same base trait at the same time

Tags:

php

traits

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;
}
like image 958
TiMESPLiNTER Avatar asked Aug 12 '15 10:08

TiMESPLiNTER


1 Answers

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;
    }
}  
like image 111
arbogastes Avatar answered Oct 09 '22 00:10

arbogastes