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

<?php
trait 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 myfunction of Trait1 on line 22.

  • On line 23 we have given an alias to myfunction of Trait2 and it can be used under name helloTrait on line 29.

  • Notice that myfunction from Trait3 is not accessible. It can also be accessed by use as in similar manner.

Note: The as operator 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

Copyright ©2026 Educative, Inc. All rights reserved