【问题标题】:Get child class name php from static function从静态函数中获取子类名 php
【发布时间】:2012-11-30 11:28:57
【问题描述】:

在 php 中,我有一个 ROOT 类,所有其他类都从该类继承。

abstract class ROOT{
    public static function getClass(){

    }
}

我希望该函数返回从该类继承的对象的类(名称)。因此,如果我创建一个对象 Tree(扩展 ROOT)并在其上调用 getClass,它应该会显示“Tree”

函数 get_class() 仅适用于对象,因此不能在静态函数中使用。 有没有办法做到这一点?

【问题讨论】:

    标签: php oop


    【解决方案1】:

    请使用get_called_class(),而不是get_class()

    【讨论】:

      【解决方案2】:

      http://www.php.net/manual/en/function.get-called-class.php

      abstract class ROOT {
          public static function getClass() {
              return get_called_class();
          }
      }
      class Tree extends ROOT {
      }
      
      $Tree = new Tree();
      echo $Tree->getClass();  // Outputs "Tree"
      

      【讨论】:

        猜你喜欢
        • 2012-08-08
        • 2012-10-18
        • 1970-01-01
        • 1970-01-01
        • 2020-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多