Why can not a Trait implement an interface in PHP?
Why can not a Trait implement an interface in PHP?
Allowing a trait to implement an interface makes all sense to me. We can treat trait as an interface that has implementation, and has no state, unlike the abstract class. So if one interface can extend another (obviously they can not implement because interfaces do not implement), why can not a trait extend as well as implement interfaces?
There is a reason. Traits can rename methods. Interfaces are contracts. They must ensure that a method has implementation within the class. trait would normally guarantee for the simple fact that it already implements the method. But if it is renamed, even though the implementation is there, it will not be accessible as the interface requires. Changed the name of the implemented method, changed the signature , and no longer meets the agreement.
If I did not have the possibility to rename, I think there could be such a possibility. But then traits could have insoluble collisions. In theory it is possible to have collision solutions without having a rename , but it would create some limitation that could be very bad for some cases and would make traits less useful.
What you can do is declare the interface in the class. If you do not have rename method, trait already resolves the agreement. If you have rename it is because you have another method that already caters to the interface.
In PHP it has an extra complicator that requires renaming because the signature only considers the method name and not its parameters.
To avoid complication, they preferred not to have a rule full of exceptions.
But you can get around in cases that make sense:
interface SomeInterface{
public function someInterfaceFunction();
}
trait SomeTrait {
function sayHello(){
echo "Hello my secret is ".static::$secret;
}
}
abstract class AbstractClass implements SomeInterface {
use SomeTrait;
}
class TestClass extends AbstractClass {
static public $secret = 12345;
function someInterfaceFunction(){ }
}
$test = new TestClass();
$test->sayHello();
See working on ideone and in PHP SandBox
I've removed the example from an OS response I do not think it says well what the problem is.