php trait编译实现,为什么PHP Trait不能实现接口?

真正的短版本更简单,因为你不能。这不是Traits如何工作。

当你写使用SomeTrait;在PHP中,你(有效地)告诉编译器将Trait中的代码复制并粘贴到正在使用的类中。

因为使用SomeTrait;是在类中,它不能添加实现SomeInterface到类,因为那必须在类外面。

“why aren’t Traits types in PHP? “

因为它们不能被实例化。 Traits实际上只是一个language construct(告诉编译器将trait代码复制并粘贴到这个类中),而不是可以被代码引用的对象或类型。

So, i want to “design” in the code that every class that want to use

my trait have to implement the interface.

这可以通过使用抽象类来实现,以使用trait然后从它扩展类。

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();

然而 – 如果你确实需要强制使用特性的任何类有一个特定的方法,我认为你可能使用你应该是抽象类的traits。

或者你有你的逻辑错误的方式。你的意思是要求实现接口的类具有某些功能,而不是如果他们有某些必须声明为实现接口的函数。

编辑

实际上,您可以在Traits中定义抽象函数,以强制类实现该方法。例如

trait LoggerTrait {

public function debug($message, array $context = array()) {

$this->log('debug', $message, $context);

}

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

}

然而,这仍然不允许你在trait中实现接口,并且仍然闻到一个糟糕的设计,因为接口比定义一个类需要满足的契约要好得多。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值