给出以下一般未知深度的类层次结构:
class P
{
protected static $var = 'foo';
public function dostuff()
{
print self::$var;
}
}
class Child extends P
{
protected static $var = 'bar';
public function dostuff()
{
parent::dostuff();
print self::$var;
}
}
class GrandChild extends Child
{
protected static $var = 'baz';
public function dostuff()
{
parent::dostuff();
print self::$var;
}
}
$c = new GrandChild;
$c->dostuff(); //prints "foobarbaz"
我可以在保留功能的同时以某种方式摆脱 dostuff()的重新定义吗?
答案 0 :(得分:2)
这应该这样做
class P
{
protected static $var = 'foo';
public function dostuff()
{
$hierarchy = $this->getHierarchy();
foreach($hierarchy as $class)
{
echo $class::$var;
}
}
public function getHierarchy()
{
$hierarchy = array();
$class = get_called_class();
do {
$hierarchy[] = $class;
} while (($class = get_parent_class($class)) !== false);
return array_reverse($hierarchy);
}
}
class Child extends P
{
protected static $var = 'bar';
}
class GrandChild extends Child
{
protected static $var = 'baz';
}
$c = new GrandChild;
$c->dostuff();