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

Rad*_*mko 5 php oop inheritance

<?php
class MyParent {

    public static function tellSomething() {
        return __CLASS__;
    }
}

class MyChild extends MyParent {

}

echo MyChild::tellSomething();
Run Code Online (Sandbox Code Playgroud)

上面的代码回声"MyParent".我怎样才能得到儿童班的名字 - 在这种情况下是"MyChild"?如果它是可能的...

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

Kin*_*nch 7

__CLASS__是一个伪常量,它始终引用定义它的类.随着late-static-binding函数get_called_class()的引入,在运行时解析了类名.

class MyParent {

  public static function tellSomething() {
    return get_called_class();
  }
}

class MyChild extends MyParent {

}

echo MyChild::tellSomething();
Run Code Online (Sandbox Code Playgroud)

(作为旁注:通常方法不需要知道他们被称为课程)


Tim*_*per 5

您所描述的内容称为Late Static Bindings,它在PHP 5.3中提供.