PHP Traits Conflict Resolution

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


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:

  • use keyword insteadof to 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();

This code will produce the following output:


Got any PHP Question?