PHP:是否可以从特征静态方法中使用特征获取类的名称? [英] PHP: Is it possible to get the name of the class using the trait from within a trait static method?
本文介绍了PHP:是否可以从特征静态方法中使用特征获取类的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以从属于该 trait 的静态方法中确定使用 trait 的类的名称吗?
Can the name of a class using a trait be determined from within a static method belonging to that trait?
例如:
trait SomeAbility {
public static function theClass(){
return <name of class using the trait>;
}
}
class SomeThing {
use SomeAbility;
...
}
获取类名:
$class_name = SomeThing::theClass();
我的直觉是,可能不是.我找不到任何其他暗示的东西.
My hunch is, probably not. I haven't been able to find anything that suggests otherwise.
推荐答案
使用 使用 static
进行后期静态绑定:
Use late static binding with static
:
trait SomeAbility {
public static function theClass(){
return static::class;
}
}
class SomeThing {
use SomeAbility;
}
class SomeOtherThing {
use SomeAbility;
}
var_dump(
SomeThing::theClass(),
SomeOtherThing::theClass()
);
// string(9) "SomeThing"
// string(14) "SomeOtherThing"
这篇关于PHP:是否可以从特征静态方法中使用特征获取类的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文