我有以下类:
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
*/
我可以将基类扩展为许多子类。
所以在我的子类中,我可以用它们自己的静态变量定义静态参数
有办法吗?或者我应该如何设计我的课程?
我认为你正在寻找的是'get_called_class()',根据php.net的定义get_called_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