我有以下课程:
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类扩展为许多子类。
所以在我的子类中,我可以通过自己的静态变量来定义静态参数。
有没有办法这样做?或者我应该如何设计课程?
答案 0 :(得分:2)
我认为你要找的是&#39; get_called_class()&#39;,根据get_called_class()的php.net定义:
&#34;获取调用静态方法的类的名称。&#34;
所以结束代码就像:
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.
// ...
}
};