php - 扩展公共静态属性
问题描述
我想扩展一个 php7.1 静态属性的类,以便让这个示例运行。
<?php
class mother {
const ONE = 1;
const TWO = 2;
const THREE = 3;
public static $desc = [
1 => 'one',
2 => 'two',
3 => 'three'
];
}
class children extends mother {
const FOUR = 4;
// how to "extends" mother::$desc ???
}
echo children::$desc[children::THREE];
echo children::$desc[children::FOUR];
exit(0);
输出 :
three
Notice: Undefined offset: 4
我必须在“儿童”课上放什么才能拥有
three
four
?
我尝试了几种语法,但由于我不知道我在做什么也不知道我必须搜索什么,所以每次尝试都失败了。似乎魔术功能可以帮助我,但我不明白如何。
解决方案
没有办法内联“扩展”父数组;你所能做的就是重新声明它:
class children extends mother {
const FOUR = 4;
public static $desc = [
1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four'
];
}
事后您可以更动态地执行此操作:
class children extends mother {
const FOUR = 4;
public static $desc = null;
}
children::$desc = mother::$desc + [4 => 'four'];