Conflict Resolution

suggest change

Using 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:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents