【问题标题】:PHP: Get the caller subclass in the base class static methodPHP:在基类静态方法中获取调用者子类
【发布时间】:2015-07-08 16:24:38
【问题描述】:

我有以下课程:

class Base {
    static $static_var = 'base_static';
    public static function static_init() {
        // HERE, I want to get the caller extended class.
        echo __CLASS__.'<br/>';
        // HERE, I want to get the caller extended static variable.
        echo static::$static_var.'<br/>';
        // Do some initialization works depends on the static_var.
        // ...
    }
};

class Children extends Base {
    // overridden
    static $static_var = 'extended_static';
};

// Call Now
Children::static_init();

/** echos:
Base
base_static
*/

/** I want to export:
Children
extended_static
*/

我可以将 Base 类扩展到许多子类。

所以在我的子类中,我可以通过它们自己的静态变量来定义静态参数。

有没有办法做到这一点?或者我应该如何设计我的课程?

【问题讨论】:

    标签: php class static


    【解决方案1】:

    我认为您正在寻找的是“get_call_class()”,根据 php.net 对 get_call_class() 的定义:

    " 获取调用静态方法的类的名称。"

    所以结束代码是这样的:

    class Base {
      static $static_var = 'base_static';
      public static function static_init() {
        $caller_class = get_called_class();
        // HERE, I want to get the caller extended class.
        echo $caller_class . '<br/>';
        // HERE, I want to get the caller extended static variable.
        echo $caller_class::$static_var.'<br/>';
        // Do some initialization works depends on the static_var.
        // ...
      }
    };
    

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

    【讨论】:

      猜你喜欢
      • 2013-04-24
      • 1970-01-01
      • 2012-05-24
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      • 1970-01-01
      相关资源
      最近更新 更多