PHP:扩展静态成员数组
我遇到以下情况:
class A { public static $arr=array(1,2); }
class B extends A { public static $arr=array(3,4); }
有什么方法可以组合这两个数组,使 B::$arr
为 1,2,3,4
?
我不需要更改这些数组,但我不能将它们声明为 const,因为 PHP 不允许使用 const 数组。https:// /stackoverflow.com/questions/ask PHP 手册指出,我只能分配字符串和常量,因此 parent::$arr + array(1,2)
不起作用,但我认为应该可以做到这一点。
I'm having the following scenario:
class A { public static $arr=array(1,2); }
class B extends A { public static $arr=array(3,4); }
Is there any way to combine these 2 arrays so B::$arr
is 1,2,3,4
?
I don't need to alter these arrays, but I can't declare them als const, as PHP doesn't allow const arrays.https://stackoverflow.com/questions/ask
The PHP manual states, that I can only assign strings and constants, so parent::$arr + array(1,2)
won't work, but I think it should be possible to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你是对的,在声明静态变量时只能分配文字和常量。解决方法是在声明类后立即在代码中分配值。在 Java 中,您可以使用静态初始化程序很好地完成此操作,但 PHP 也不支持这些,因此我们必须自己定义和调用方法:
另请注意使用
array_merge
而不是 union (+
) 运算符 - 联合运算符不会按照您的预期组合数组,因为它们具有相同的数字键 - 第一个是array(0=>1, 1=>2 )
,第二个是array(0=>3, 1=>4)
;它们的并集仅包含每个键一次,因此您最终会得到(1,2)
或(3,4)
,具体取决于您联合的顺序他们。You're correct, you can only assign literals and constants when declaring a static variable. The work-around would be to assign the value in code just after the class is declared. In Java you could do this nicely with a static initialiser, but PHP doesn't support those either, so we have to define and call a method ourselves:
Also note the use of
array_merge
instead of the union (+
) operator - the union operator won't combine the arrays as you intend, as they have identical numerical keys - the first isarray(0=>1, 1=>2)
, second isarray(0=>3, 1=>4)
; the union of them will only contain each key once, so you'll either end up with(1,2)
or(3,4)
depending on the order you union them.是的,您只需要变得有点花哨,因为您将无法定义静态变量。
输出:
也很好,因为您也可以访问原始数组:
Yes, you just need to get a bit fancy as you won't be able to define a static variable.
Output:
Also good since you can access the original arrays too: