在父类的构造函数,做这样的事情:
<?php
abstract class ParentClass {
protected $foo = array(
'bar' => 'Parent Value',
'baz' => 'Some Other Value',
);
public function __construct() {
$parent_vars = get_class_vars(__CLASS__);
$this->foo = array_merge($parent_vars['foo'], $this->foo);
}
public function put_foo() {
print_r($this->foo);
}
}
class ChildClass extends ParentClass {
protected $foo = array(
'bar' => 'Child Value',
);
}
$Instance = new ChildClass();
$Instance->put_foo();
// echos Array ([bar] => Child Value [baz] => Some Other Value)
基本上,魔法来自get_class_vars()
功能,这将返回在特定的类中设置的属性,无论价值设置在儿童班。
如果你想获得与该函数的父类值,你可以做任何的从父类本身如下:get_class_vars(__CLASS__)
或get_class_vars(get_class())
如果你想获得ChildClass值,你可以做以下来自ParentClass或ChildClass:get_class_vars(get_class($this))
,尽管这与访问$this->var_name
(显然,这取决于变量范围)相同。
好吧我想我找到了一个使用反射的解决方案。在A的构造函数中,我可以这样做:`$ r = new ReflectionClass();提取($ r-> getDefaultProperties());` – 2011-02-15 23:55:32