2

we have a small pseudocode scenario in our project:

trait headFunction {
    protected function doStuffWithParam($param){
       return $param;
    }
}

trait extA {
    use headFunction;

    protected function doExtAStuff($param){
        ...
        return $this->doStuffWithParam($param);
    }
}

trait extB {
    use headFunction;

    protected function doExtBStuff($param){
        ...
        return $this->doStuffWithParam($param);
    }
}

class classUsingTraits(){
    use extA, extB;

    ...
}

But there is collision:

Trait method doStuffWithParam has not been applied, because there are collisions with other trait methods on test in....

Unfortunately traits has no extend option.

How to avoid problem with collision without moving headFunction to classUsingTraits - is there any soloution? We looks in PHP documentation, but there is soloution only for 2 traits - we have traits like this about 10+-.. and we cannot use it.

Is there any way how to solve this?

Thanks you for help!

Filip
  • 212
  • 3
  • 12
  • 1
    The problem PHP has with this code is that there's a chance you do something different when doStuff is called from extA rather than extB. If it's always the same stuff being done you can just resolve the collision in the class using `use extA, extB { extA::doStuffWithParam insteadof extB; }` – apokryfos Feb 14 '17 at 11:07
  • But what about when you want to use 3 or more traits? – Filip Feb 14 '17 at 11:08
  • 1
    Same idea, it kind of an indication that traits are probably not the ideal solution to your situation. It's also why most programming languages are not offering multiple inheritance. – apokryfos Feb 14 '17 at 11:19
  • 2
    The point about traits is: it's copy and paste solution, nothing more (just done by interpreter). As a "copy and paste paradigm", you have to ensure that won't have collisions. – Gabriel Heming Feb 14 '17 at 11:42

0 Answers0