简体   繁体   中英

How to get parent namespace from Trait

I created a trait and i want to be able to get the namespace of the class using the trait. is this possible? self::class gives me the class name of the parent but not the entire namespace

You can use ReflectionClass->getNamespaceName() with the reflection of self::class.

MyTrait.php

namespace MyTraitNamespace;

Trait MyTrait{
    public function echoClassNamespace()
    {
        $ref = new \ReflectionClass(self::class);
        echo $ref->getNamespaceName(); //Will echo MyClassNamespace
    }

    public function echoTraitNamespace()
    {
        echo __NAMESPACE__; //Will echo MyTraitNamespace
    }
}

MyClass.php

namespace MyClassNamespace;

use MyTraitNamespace\MyTrait;

class MyClass{
    use MyTrait;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM