这是我之前关于 resolving the diamond issue in php 的问题的后续内容。 .
正如我在那个问题中所说,我通过使用特征并将类的实例传递给特征的方法来解决我的问题。如:
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);
}
}
但是,我仍然对此感到不舒服,因为我认为这不是真正应该使用特征的方式。在我的阅读中,我还没有找到任何方法来访问特征中的类成员(使
$this
在特征中引用使用它的类)。这可能吗?还是有另一种方法来实现类似的行为?在阅读了一些答案后...
以前我以为我在使用
$this->...
时收到了错误在 trait 内部,这让我相信 trait 无法访问与底层类有关的任何内容。阅读答案后,我尝试更改我的代码以使用 $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;
}
更清晰,更容易理解,但提供相同的功能。
最佳答案
如果您在类中使用 trait,那么该 trait 可以完全访问所有类的成员,反之亦然 - 您可以从类本身调用私有(private) trait 方法。
将特征视为从字面上复制/粘贴到类主体中的代码。
例如:
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"
在我看来,在特征中引用类并不是使用它们的最佳方式,但没有什么能阻止任何人这样做。
关于php - 如何访问特征中的类成员(或获得类似的行为)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32364039/