如何获取内部带有命名空间的特征名称?
How to get the trait name with namespace inside itself?
我想知道是否有办法在其内部获取 traits 命名空间,我知道我可以使用 self::class
获取 classname,但在 traits 内部它获取使用特征的 class 的命名空间,我不想输入它的固定名称,如 new ReflectionClass('trait')
是否有任何函数或常量可以做到这一点?
我对你的问题有点困惑,但如果你需要特征的完全限定名称,那么你可以使用 __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
}
}
现在,使用另一个命名空间声明一个 class 并在此 class 中使用该特征:
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__
(since 5.4.0) and __NAMESPACE__
(since 5.3.0) is used so use which one is needed. Tested in php v-5.4.0
. Check the demo here.
此外,如果您想从正在使用它的 class 中获取特征的完全限定名称,那么您可以使用 NameOfTheTrait::class
(NameOfTheClass::class
/NameOfTheInterface::class
) 但自 php v-5.5
.
起可用
使用self::class
时也要小心。 self::class
将在您使用它的地方给出 class 的完全限定名称,因为 self
自 self
是在编译期间确定的,因此如果您在使用 self::class
语句的地方继承 class,您可能会得到意想不到的结果。换句话说,如果您从子 class 调用任何静态方法,那么调用上下文仍将是父 class 如果您在父 class 中使用 self
,则在这种情况下,您需要使用 static
而不是 self
。这实际上是另一个主题,因此请阅读有关 Late Static Binding 的 php 手册的更多信息。
我想知道是否有办法在其内部获取 traits 命名空间,我知道我可以使用 self::class
获取 classname,但在 traits 内部它获取使用特征的 class 的命名空间,我不想输入它的固定名称,如 new ReflectionClass('trait')
是否有任何函数或常量可以做到这一点?
我对你的问题有点困惑,但如果你需要特征的完全限定名称,那么你可以使用 __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
}
}
现在,使用另一个命名空间声明一个 class 并在此 class 中使用该特征:
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__
(since 5.4.0) and __NAMESPACE__
(since 5.3.0) is used so use which one is needed. Tested in php v-5.4.0
. Check the demo here.
此外,如果您想从正在使用它的 class 中获取特征的完全限定名称,那么您可以使用 NameOfTheTrait::class
(NameOfTheClass::class
/NameOfTheInterface::class
) 但自 php v-5.5
.
使用self::class
时也要小心。 self::class
将在您使用它的地方给出 class 的完全限定名称,因为 self
自 self
是在编译期间确定的,因此如果您在使用 self::class
语句的地方继承 class,您可能会得到意想不到的结果。换句话说,如果您从子 class 调用任何静态方法,那么调用上下文仍将是父 class 如果您在父 class 中使用 self
,则在这种情况下,您需要使用 static
而不是 self
。这实际上是另一个主题,因此请阅读有关 Late Static Binding 的 php 手册的更多信息。