【发布时间】:2016-10-25 12:14:03
【问题描述】:
我有一个关于在 PHP 中使用 Trait 和 Interfaces 的问题。
具有 foobar 功能的特征
<?php
trait FoobarTrait
{
protected $foobar;
public function setFoobar($foobar)
{
$this->foobar = $foobar
}
public function getFoobar()
{
return $this->foobar;
}
}
具体的Interface来指定如何使用Trait
<?php
interface FoobarInterface
{
public function setFoobar($foobar);
public function getFoobar();
}
我想在课堂上使用 foobar 功能。最好的方法是什么?
需要用接口实现并指定特征还是诱导行为?
<?php
class FoobarClass implements FoobarInterface
{
use FoobarTrait;
}
或者这个
<?php
class FoobarClass
{
use FoobarTrait;
}
感谢您的回复和辩论;)
【问题讨论】:
-
有了这个接口,你可以用 instanceof 测试你的对象,在这种情况下做一些事情
-
“最好的方法是什么?”的答案总是“取决于”
-
This answer 可能会有所帮助
-
instanceof 可与特征以及接口一起使用,但您不能键入提示特征。因此,如果您绝对肯定要使用特征,我建议将它们与接口配对,因为我已经介绍过 here。
-
总是实现接口。 traut 只是语言助手的复制和粘贴。如果你有一个可以分离的功能,那么这个界面就很容易使用。
标签: php symfony design-patterns