我希望能够获得已故的静态绑定类的父级。我写了一个无法运行的代码示例来澄清我的意思:
class A
{
public static function getCombinedProperties()
{
$a = static::$properties; // Late static binding means this will work
if(isset(static::parent::$properties)) // Calling static::parent obviously does not work
$a = array_merge_recursive($a, static::parent::$properties);
return $a;
}
}
class B extends A
{
public static $properties = ['fruits' => ['pineapple', 'mango']];
}
class C extends B
{
public static $properties = ['fruits' => ['apple', 'banana'], 'vegetables' => ['carrot', 'pea']];
}
B::getCombinedProperties(); //desired output ['fruits' => ['pineapple', 'mango']]
C::getCombinedProperties(); //desired output ['fruits' => ['apple', 'banana', 'pineapple', 'mango'], 'vegetables' => ['carrot', 'pea']]
当从C类调用该方法时,A类是否可以访问B类的$ properties属性?
答案 0 :(得分:1)
这似乎有用,虽然感觉很讨厌:
class A
{
public static function getCombinedProperties()
{
$a = static::$properties; // Late static binding means this will work
$class = new \ReflectionClass(get_called_class());
$parent = $class->getParentClass();
$parentName = $parent->getName();
if(isset($parentName::$properties))
$a = array_merge_recursive($a, $parentName::$properties);
return $a;
}
}