这是我先前有关解决php中的菱形问题的问题的后续解决方案。
当我陈述该问题时,我通过使用trait并将类的实例传递给trait的方法来解决我的问题。如:
trait SecurityTrait
{
public function beforeExecuteRouteTrait($controller, Dispatcher $dispatcher)
{
// Do something that makes use of methods/members of the controller
}
}
class AppController extends Controller
{
use SecurityTrait;
public function beforeExecuteRoute(Dispatcher $dispatcher)
{
return $this->beforeExecuteRouteTrait($this, $dispatcher);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我仍然对此感到不舒服,因为我认为这并不是应该真正使用特质的方式。在我的阅读中,我还没有发现任何方式在访问类成员的特征(化妆$this
内部特征指的是类使用它)。这可能吗?还是有另一种方式来实现类似的行为?
阅读了一些答案之后...
以前,我以为$this->...
在特质内部使用时会遇到错误,这使我相信特质无法访问与基础类有关的任何内容。阅读答案后,我尝试更改代码以$this->...
再次在特征中使用,并且它可以正常工作-这意味着几周前的错别字使我头疼不已...
前面给出的示例现在看起来像这样
trait SecurityTrait
{
public function beforeExecuteRoute(Dispatcher $dispatcher)
{
// Do something that makes use of methods/members of the controller
}
}
class AppController extends Controller
{
use SecurityTrait;
}
Run Code Online (Sandbox Code Playgroud)
更干净,更容易理解,但提供相同的功能。
如果在类内部使用特征,则该特征具有对所有类成员的完全访问权限,反之亦然-您可以从类本身调用私有特征方法。
将特征视为从字面上被复制/粘贴到类主体中的代码。
例如:
trait Helper
{
public function getName()
{
return $this->name;
}
private function getClassName()
{
return get_class($this);
}
}
class Example
{
use Helper;
private $name = 'example';
public function callPrivateMethod()
{
// call a private method on a trait
return $this->getClassName();
}
}
$e = new Example();
print $e->getName(); // results in "example"
print $e->callPrivateMethod(); // results in "Example"
Run Code Online (Sandbox Code Playgroud)
在我看来,在traits中引用类不是使用它们的最佳方法,但是没有什么可以阻止任何人这样做。