PHP: 如何知道哪个 class 调用了一个 Trait 里面的逻辑?

PHP: How to know which class called the logic inside a Trait?

在 Laravel 中,我有几个 Artisan 命令,它们执行不同的操作但共享一些逻辑。为了不再重复我自己,我将该逻辑转移到一个特征(主要是 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) (built: Aug 19 2018 07:16:54) ( NTS )

get_class returns 传递对象的class 名称。由于您处于对象的方法之一,继承自特征,您可以使用它来访问当前对象。

$classThatCalledThis = get_class($this);

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

根据magic constants page

Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.

你可以使用 __CLASS__:

dd(__CLASS__);

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

dd(static::class);

一个fiddle是here,它告诉你__CLASS__static::class之间的区别。