[英]PHP accessing child's and grandchild's static properties from parent
Given the following class hierarchy of in general unknown depth: 给定以下类层次结构的一般未知深度:
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"
Can I somehow get rid of the redefinitions of dostuff() while maintaining functionality? 在保持功能的同时,我可以以某种方式摆脱dostuff()的重新定义吗?
This should do it 这应该做到这一点
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.