为什么 PHP Trait 不能实现接口?

我想知道为什么 PHP Trait (PHP 5.4)不能实现接口。

来自 user1460043的更新的答案 = > ... 不能要求使用它来实现特定接口 的类

我明白这可能是显而易见的,因为人们可能认为,如果 Class A使用的是实现 interface ITrait T,那么 Class A就应该非直接实现 interface I(这是不正确的,因为 Class A可以重命名 trait 方法)。

在我的例子中,trait 是从使用 trait 的类实现的接口调用方法。

Trait 实际上是接口的一些方法的实现。 因此,我想在代码中“设计”每个想要使用 trait 的类都必须实现接口。这将允许 Trait 使用接口定义的类方法,并确保它们存在于类中。

47762 次浏览

The really short version is simpler because you can't. That's not how Traits work.

When you write use SomeTrait; in PHP you are (effectively) telling the compiler to copy and paste the code from the Trait into the class where it's being used.

Because the use SomeTrait; is inside the class, it can't add implements SomeInterface to the class, because that has to be outside the class.

"why aren't Traits types in PHP? "

Because they can't be instantiated. Traits are really just a language construct (telling the compiler to copy and paste the trait code into this class) as opposed to an object or type that can be referenced by your code.

So, i want to "design" in the code that every class that want to use my trait have to implement the interface.

That can be enforced using an abstract class to use the trait and then extending classes from it.

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(){
//Trying to instantiate this class without this function uncommented will throw an error
//Fatal error: Class TestClass contains 1 abstract method and must therefore be
//declared abstract or implement the remaining methods (SomeInterface::doSomething)
//}
}


$test = new TestClass();


$test->sayHello();

However - if you do need to enforce that any class that uses a Trait has a particular method, I think you may be using traits where you should have been abstract classes in the first place.

Or that you have your logic the wrong way round. You're meant to require classes that implement interfaces have certain functions, not that if they have certain functions that they must declare themselves as implementing an interface.

Edit

Actually you can define abstract functions inside Traits to force a class to implement the method. e.g.

trait LoggerTrait {


public function debug($message, array $context = array()) {
$this->log('debug', $message, $context);
}


abstract public function log($level, $message, array $context = array());
}

However this still doesn't allow you to implement the interface in the trait, and still smells like a bad design, as interfaces are much better than traits at defining a contract that a class needs to fulfill.

[...] to "design" in the code that every class that want to use my trait have to implement the interface. That would allow the Trait to use class methods defined by the interface and be sure they are existing in the class.

This sounds very reasonable and I would not say that there has to be anything wrong with your design. Traits have been suggested with this idea in mind, see the second point here:

  • A trait provides a set of methods that implement behaviour.
  • A trait requires a set of methods that serve as parameters for the provided behaviour.
  • [...]

Schärli et al, Traits: Composable Units of Behaviour, ECOOP’2003, LNCS 2743, pp. 248–274, Springer Verlag, 2003, Page 2

So it would be maybe more appropriate to say that you want a trait to require an interface, not to "implement" it.

I do not see a reason why it should be impossible to have this "trait requires (its consumer classes to implement) an interface" feature in PHP, but currently it seems to be missing.

As @Danack notes in his answer, you can use abstract functions in the trait to "require" them from classes that use the trait. Unfortunately you can not do this with private functions.

There's a RFC: Traits with interfaces suggests following to be added to the language:

trait SearchItem implements SearchItemInterface
{
...
}

Methods required by the interface can either be implemented by the trait, or declared as abstract, in which case it is expected that class that uses the trait implements it.

This feature is currently not supported by the language, but it is under consideration (current status of the RFC is: Under Discussion).

I agree with the response of @Danack, however I will complement it a little.

The really short version is simpler because you can't. That's not how Traits work.

I can only think of few cases in which what you request is necessary and is more evident as a design problem than as a language failure. Just imagine that there is an interface like this:

interface Weaponize
{
public function hasAmmunition();
public function pullTrigger();
public function fire();
public function recharge();
}

A trait has been created that implements one of the functions defined in the interface but in the process uses other functions also defined by the interface, prone to the error that if the class that uses the feature does not implement the interface everything fails to pull the trigger

trait Triggerable
{
public function pullTrigger()
{
if ($this->hasAmmunition()) {
$this->fire();
}
}
}


class Warrior
{
use Triggerable;
}

An easy solution is simply to force the class that uses the trait to implement those functions as well:

trait Triggerable
{
public abstract function hasAmmunition();
public abstract function fire();


public function pullTrigger()
{
if ($this->hasAmmunition()) {
$this->fire();
}
}
}

So the trait isn't completely dependent on the interface, but a proposal to implement one of its functions, since when using the trait the class will demand the implementation of the abstract methods.

Final design

interface Weaponize
{
public function hasAmmunition();
public function pullTrigger();
public function fire();
public function recharge();
}


trait Triggerable
{
public abstract function hasAmmunition();
public abstract function fire();


public function pullTrigger()
{
if ($this->hasAmmunition()) {
$this->fire();
}
}
}




class Warrior implements Weaponize
{
use Triggerable;


public function hasAmmunition()
{
// TODO: Implement hasAmmunition() method.
}


public function fire()
{
// TODO: Implement fire() method.
}


public function recharge()
{
// TODO: Implement recharge() method.
}
}

Please excuse my English