How to resolve naming conflicts in traits?
Traits allow us to group methods and functionalities together in a set of reusable code. Traits are similar to classes but can not be instantiated into objects.
Note: To learn more about traits in PHP, click here.
You can inherit from multiple traits by providing a comma-separated list before the use keyword.
Sometimes, inserting multiple traits in a class can cause naming conflicts. This happens because of sharing the same signature by different methods from different traits, and as a result, a fatal error is encountered.
We can use insteadof and as operators to resolve such issues explicitly.
Conflict resolution
Choose one of the colliding functions explicitly using insteadof operator.
Basic syntax
Trait1::myfunction insteadof Trait2;
This will choose myfunction from Trait1 over Trait2.
Running example
<?phptrait Trait1 {public function myfunction() {echo "Hello World! \n";}}trait Trait2 {public function myfunction() {echo "Hello Trait\n";}}trait Trait3 {public function myfunction() {echo "Hello!\n";}}class HelloFromTrait {use Trait1, Trait2, Trait3 {Trait1::myfunction insteadof Trait2,Trait3;Trait2::myfunction as helloTrait;}}$t = new HelloFromTrait();$t->myfunction();$t->helloTrait();?>
Explanation
-
We have resolved the conflict by choosing
myfunctionofTrait1on line 22. -
On line 23 we have given an alias to
myfunctionofTrait2and it can be used under namehelloTraiton line 29. -
Notice that
myfunctionfromTrait3is not accessible. It can also be accessed by useasin similar manner.
Note: The
asoperator does not change the method’s signature but only assigns an alternative alias to it. So your implementation for the rest of the code will not be affected.
Free Resources