是否可以从属于某个特征的静态方法中确定使用该特征的类的名称?
例如:
trait SomeAbility {
public static function theClass(){
return <name of class using the trait>;
}
}
class SomeThing {
use SomeAbility;
...
}
Run Code Online (Sandbox Code Playgroud)
获取班级名称:
$class_name = SomeThing::theClass();
Run Code Online (Sandbox Code Playgroud)
我的直觉可能不是。我没有找到其他建议的东西。
使用后期静态绑定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"
Run Code Online (Sandbox Code Playgroud)