【问题标题】:How to get class name from static child method如何从静态子方法中获取类名
【发布时间】:2011-06-29 13:23:21
【问题描述】:
<?php
class MyParent {

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

class MyChild extends MyParent {

}

echo MyChild::tellSomething();

上面的代码回显“MyParent”。我怎样才能得到子类的名字——在这种情况下是“MyChild”?如果可以的话……

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

【问题讨论】:

标签: php oop inheritance


【解决方案1】:

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

class MyParent {

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

class MyChild extends MyParent {

}

echo MyChild::tellSomething();

(作为旁注:通常方法不需要知道它们被调用时所在的类)

【讨论】:

    【解决方案2】:

    您所描述的称为Late Static Bindings,它在 PHP 5.3 中可用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 2016-08-04
      • 2012-03-04
      • 1970-01-01
      • 2022-10-06
      相关资源
      最近更新 更多