What happens if I use a class in two different traits, and both have a method with the same name but different implementations of this method?
Asked
Active
Viewed 159 times
0
-
5Try to imagine all life as you know it stopping instantaneously and every molecule in your body exploding at the speed of light. – AbraCadaver Oct 05 '16 at 17:39
-
1@AbraCadaver Here's a [visual reference](https://media.giphy.com/media/EldfH1VJdbrwY/giphy.gif) to go along with that – Machavity Oct 05 '16 at 17:47
-
@Machavity: I was talking about, _total protonic reversal_... – AbraCadaver Oct 05 '16 at 17:48
-
1Possible duplicate of [Collisions with other trait methods](http://stackoverflow.com/questions/25064470/collisions-with-other-trait-methods) – Michael Gaskill Oct 05 '16 at 23:03
1 Answers
2
Short answer
Long answer
Say you have a class Foo that uses traits A and B:
class Foo {
use A, B;
}
Where both traits have a method with a similar name, but different implementation (the implementation doesn't matter, really):
trait A {
public function bar() {
return true;
}
}
trait B {
public function bar() {
return false;
}
Traits work by extending the class horizontally. Simply put - just adding any new contents to the class. And all works fine till there's any doubling in trait methods and properties. Then you have yourself a fatal error if this conflict is not explicitly resolved.
The sweet part is, you can resolve this conflict by specifying which method from which trait to use:
class Foo {
use A, B {
B::bar insteadof A;
}
}
You can also save the other method from oblivion by using alias for it:
class Foo {
use A, B {
B::bar insteadof A;
A::bar as barOfA;
}
}
The manual has traits farely well documented, go check it out.

BVengerov
- 2,947
- 1
- 18
- 32