【问题标题】:How to get the trait name with namespace inside itself?如何获取内部带有命名空间的特征名称?
【发布时间】:2018-07-19 08:54:47
【问题描述】:

我想知道是否有办法在其内部获取特征命名空间,我知道我可以使用self::class 来获取类名,但在特征内部它会获取使用特征的类的命名空间,我不想像new ReflectionClass('trait')那样输入固定的名称

是否有任何函数或常量可以做到这一点?

【问题讨论】:

    标签: php namespaces traits


    【解决方案1】:

    我对你的问题有点困惑,但如果你需要特征的完全限定名称,那么你可以使用 __TRAIT__ 魔法常数,如果你只需要特征的命名空间,那么你可以使用 __NAMESPACE__ .例如,使用命名空间声明一个特征:

    namespace App\Http\Controllers\Traits;
    
    trait Methods
    {
        public function getNamespace()
        {
            // Get fully qualified name of the trait
            echo __TRAIT__; // App\Http\Controllers\Traits\Methods
    
            echo PHP_EOL;
    
            // Get namespace of the trait
            echo __NAMESPACE__; // App\Http\Controllers\Traits
        }
    }
    

    现在,使用另一个命名空间声明一个类,并在该类中使用该特征:

    namespace App\Http\Controllers;
    
    use App\Http\Controllers\Traits\Methods;
    
    class TraitController
    {
        use Methods;
    
        public function index()
        {
            // Call the method declared in trait
            $this->getNamespace();
        }
    }
    
    
    (new TraitController)->index();
    

    使用了预定义的magic constants__TRAIT__(自 5.4.0 起)和 __NAMESPACE__(自 5.3.0 起),所以使用哪个是需要的。在php v-5.4.0 中测试。查看演示here

    另外,如果你想从使用它的类中获取特征的完全限定名,那么你可以使用NameOfTheTrait::class (NameOfTheClass::class/NameOfTheInterface::class),但这是从php v-5.5 开始可用的。

    在使用self::class 时也要小心。 self::class 将给出您使用它的类的完全限定名称,因为 self 总是引用词法范围(它在物理上使用的地方),因为 self 的范围是在编译期间确定的,所以你如果你继承一个使用self::class 语句的类,可能会得到意想不到的结果。换句话说,如果您从子类调用任何静态方法,那么如果您在父类中使用self,则调用上下文仍将是父类,在这种情况下,您需要使用static 而不是self .这实际上是另一个话题,所以请阅读更多关于Late Static Binding的php手册。

    【讨论】:

      猜你喜欢
      • 2014-05-10
      • 1970-01-01
      • 2011-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2014-09-14
      相关资源
      最近更新 更多