【问题标题】:PHP: How to know which class called the logic inside a Trait?PHP:如何知道哪个类调用了 Trait 中的逻辑?
【发布时间】:2018-12-18 09:52:03
【问题描述】:

在 Laravel 中,我有几个 Artisan 命令,它们做不同的事情,但共享一些逻辑。为了不重复我自己,我将这个逻辑移到了一个 trait 上(主要是 handle() 方法。但是一切都很顺利……

如果我有FooCommandBarCommand 以及两个命令use BazTrait 然后在BazTrait 内:

trait BazTrait
{
    public function handle()
    {
        // how to get the name of the class (FooCommand or BarCommand)
        // that called this code right now?

        dd(classThatCalledThis) // expect to dump either FooCommand or BarCommand
    }
}

也许我错过了什么?感谢您的任何提示。

vagrant@homestead:~/Code/foo$ php -v PHP 7.2.9-1+ubuntu18.04.1+deb.sury.org+1(cli)(构建:2018 年 8 月 19 日 07:16:54)(NTS)

【问题讨论】:

  • __CLASS__?

标签: php php-7.2


【解决方案1】:

根据magic constants page

请注意,从 PHP 5.4 开始,__CLASS__ 也适用于特征。在 trait 方法中使用时,__CLASS__ 是使用 trait 的类的名称。

你可以使用__CLASS__:

dd(__CLASS__);

但是最可靠的方式(在继承和所有这些东西的情况下)是:

dd(static::class);

小提琴是here,它显示了__CLASS__static::class 之间的区别。

【讨论】:

  • 哦,废话!我今天显然太累了。谢谢! ? ??
  • 我会接受这个以获得更多信息。再次感谢。
  • static::class添加了更可靠的方法。
【解决方案2】:

get_class 返回传递对象的类名。由于您在对象的方法之一中,从 trait 继承,您可以使用它来访问当前对象。

$classThatCalledThis = get_class($this);

http://php.net/manual/fr/function.get-class.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多