Conflict Resolution
suggest changeUsing several traits in one class can produce conflicting methods. You have to resolve those conflicts yourself.
For example, let’s create this hierarchy:
trait MeowTrait {
public function say() {
print "Meow \n";
}
}
trait WoofTrait {
public function say() {
print "Woof \n";
}
}
abstract class UnMuteAnimals {
abstract function say();
}
class Dog extends UnMuteAnimals {
use WoofTrait;
}
class Cat extends UnMuteAnimals {
use MeowTrait;
}
Now, let’s try to create the following class:
class TalkingParrot extends UnMuteAnimals {
use MeowTrait, WoofTrait;
}
PHP raises a fatal error. The current wording is:
Fatal error: Trait method WoofTrait::say has not been applied as TalkingParrot::say, because of collision with MeowTrait::say
To resolve this conflict, we could do this:
- use keyword
insteadofto use the method from one trait instead of method from another trait - create an alias for the method with a construct like
WoofTrait::say as sayAsDog;
class TalkingParrotV2 extends UnMuteAnimals {
use MeowTrait, WoofTrait {
MeowTrait::say insteadof WoofTrait;
WoofTrait::say as sayAsDog;
}
}
$talkingParrot = new TalkingParrotV2();
$talkingParrot->say();
$talkingParrot->sayAsDog();
This code will produce the following output:
Meow
Woof
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents