如何从静态子方法中获取类名


How to get class name from static child method

<?php
class MyParent {
    public static function tellSomething() {
        return __CLASS__;
    }
}
class MyChild extends MyParent {
}
echo MyChild::tellSomething();

上面的代码回声为"MyParent"。如何获取子类的名称——在这种情况下是"MyChild"?如果可能的话。。。

我只需要知道哪个孩子在调用继承的方法。

__CLASS__是一个伪常数,它总是指定义它的类。late-static-binding引入了函数get_called_class(),用于在运行时解析类名。

class MyParent {
  public static function tellSomething() {
    return get_called_class();
  }
}
class MyChild extends MyParent {
}
echo MyChild::tellSomething();

(附带说明:通常方法不需要知道调用它们的类(

您所描述的被称为Late静态绑定,它在PHP 5.3中提供。