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
Asked
Active
Viewed 959 times
2

Ruben Gonzalez
- 143
- 1
- 15
-
1Did you try `__NAMESPACE__`? https://3v4l.org/oRqvK – Lawrence Cherone Oct 20 '18 at 21:36
-
Have you tried `static::class`? https://stackoverflow.com/questions/5197300/new-self-vs-new-static/5197655 – Travis Britz Oct 20 '18 at 21:36
-
Not reproducible: https://3v4l.org/NQQEk – Devon Bessemer Oct 20 '18 at 21:41
-
1@LawrenceCherone actually that won't work, that'll return the namespace of the trait, not the class. – Devon Bessemer Oct 20 '18 at 21:46
1 Answers
4
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;
}

Stefmachine
- 382
- 4
- 11