In you include a trait that contains a method with the same name as a method in your class then you can rename the trait method on the fly.
Take the following trait.
trait AnExampleTrait {
public function someMethod() {
print 'trait method';
}
}
And the following class.
class AnExampleClass {
public function someMethod() {
print 'class method';
}
}
If we just introduced the trait into the class then PHP will just ignore the trait method since a method already exists.
class AnExampleClass {
use AnExampleTrait;
public function someMethod() {
print 'class method';
}
}
$obj = new AnExampleClass();
$obj->someMethod(); // prints "trait method";
To get around this we can use a syntax available with the trait that allows us to rename methods on the fly, as they are injected into the class.
Here is an example of this in action.
class AnExampleClass {
use AnExampleTrait {
someMethod as methodOfAnotherName;
}
public function someMethod() {
print 'class method';
}
}
$obj = new AnExampleClass();
$obj->someMethod(); // prints "class method";
$obj->methodOfAnotherName(); // prints "class method";
We can't use the original method, but this does give us access to the method in the trait that we wouldn't otherwise have access to.
Add new comment