What happens if I use two different traits in a class, and both have a method with the same name, but different implementations in this method?
What happens if I use two different traits in a class, and both have a method with the same name, but different implementations in this method?
In a way, yes. Not entirely because a trait could not have been. But you can get subtype and subclass of various types with it.
If the class has an implementation of the method it will be considered and implementations of the traits will be disregarded. The same is true if the method in trait has no implementation. Obviously the class is required to implement, unless another trait provides a conceptually acceptable implementation.
When there is conflict, an error is generated and the code does not work. It is possible to resolve the conflict and allow the correct operation. The documentation shows how it is resolved:
trait A {
public function smallTalk() {
echo 'a';
}
public function bigTalk() {
echo 'A';
}
}
trait B {
public function smallTalk() {
echo 'b';
}
public function bigTalk() {
echo 'B';
}
}
class Talker {
use A, B {
B::smallTalk insteadof A;
A::bigTalk insteadof B;
}
}
class Aliased_Talker {
use A, B {
B::smallTalk insteadof A;
A::bigTalk insteadof B;
B::bigTalk as talk;
}
}
See working on ideone or in PHP SandBox .
So there is a syntax that determines which of the ambiguous traits should be used in each situation. In this example the smallTalk()
used will be trait B
. The bigTalk()
will be A
. And if you use a ninth method called talk()
that will be the same as calling bigTalk()
of B
. smallTalk()
of A
is not accessible.
Suppose you have two or more classes that need to use a common method, it may be possible to use Traits.
Traits are mechanisms that help reuse code, and serve perfectly to solve the problem of lack of multiple inheritance, as PHP does not support multiple inheritance. Traits was released from version 5.4.0 of PHP.
A Trait can not be instantiated or have its methods called directly and must be incorporated into a class.
The syntax for embedding a trait into a class is through the reserved word use
.
class Base {
public function sayStack() {
echo 'Stack ';
}
}
trait SayOverflow {
public function sayOverflow() {
parent::sayStack();
echo 'Overflow!';
}
}
class MyStackOverflow extends Base {
use SayOverflow;
}
$o = new MyStackOverflow();
$o->sayOverflow();
References:
php.net documentation
When should I use Inheritance, Abstract Class, Interface, or a Trait?