Interview frequency: …
Short answer
Use insteadof to choose the method from the preferred Trait, and as to give another method an alias or change its visibility.
Explanation
Traits provide horizontal code reuse in a language with single inheritance. If two Traits, A and B, both define a method named doWork(), using both causes a Fatal Error. Resolve the conflict explicitly inside the class with insteadof, and use as to keep the other method under an alias.
Code example
class App {
use TraitA, TraitB {
TraitA::doWork insteadof TraitB;
TraitB::doWork as doWorkFromB;
}
}Common mistakes
- Using Traits as an arbitrary replacement for inheritance and dependency injection, creating large, untestable objects.