Why can’t a Trait implement an interface?

Asked

Viewed 79 times

7

Why a Trait cannot implement an interface in PHP?

1 answer

8


Allow a trait implement an interface makes perfect sense to me. We can face the trait as an interface that has implementation, and has not been, unlike the abstract class. So if one interface can extend another (obviously they cannot implement, because interfaces do not implement), why a trait cannot either extend or implement interfaces?

There is a reason. Traits can rename methods. Interfaces are contracts. They must ensure that a method has implementation within the class. The trait Normally I would guarantee for the simple fact that it already implements the method. But if it is renamed, even if the implementation is there, it cannot be accessed as the interface requires. Changed the name of the implemented method, changed the signing and no longer complies with the contract.

If I didn’t have the possibility to rename, I think there might be that possibility. But then traits could have insoluble collisions. Theoretically it is possible to have collision solutions without having a name, but would create some limitation that might 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 don’t have name method, the trait already resolves the contract. If you have name is because it has another method that already meets the interface.

In PHP there is 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();

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I took the example of a response from the OS I don’t think it says what the problem is.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.