Trying to use several traits into one class could result in issues involving conflicting methods. You need to resolve such conflicts manually.
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;
}
The php interpreter will return a fatal error:
Fatal error: Trait method say has not been applied, because there are collisions with other trait methods on TalkingParrot
To resolve this conflict, we could do this:
insteadof
to use the method from one trait instead of method from another traitWoofTrait::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