PHP:是否可以从特征静态方法中使用特征获取类的名称?

use*_*603 3 php traits

是否可以从属于某个特征的静态方法中确定使用该特征的类的名称?

例如:

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)

我的直觉可能不是。我没有找到其他建议的东西。

Yos*_*shi 7

使用后期静态绑定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)

https://3v4l.org/mfKYM