php 公共静态变量值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6500732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Public static variable value
提问by Alex
I'm trying to declare a public static variable that is a array of arrays:
我正在尝试声明一个公共静态变量,它是一个数组数组:
class Foo{
public static $contexts = array(
'a' => array(
'aa' => something('aa'),
'bb' => something('bb'),
),
'b' => array(
'aa' => something('aa'),
'bb' => something('bb'),
),
);
// methods here
}
function something($s){
return ...
}
But I get a error:
但我收到一个错误:
Parse error: parse error, expecting `')'' in ...
解析错误:解析错误,在 ...
回答by deceze
You can't use expressions when declaring class properties. I.e. you can't call something()
here, you can only use static values. You'll have to set those values differently in code at some point.
声明类属性时不能使用表达式。即你不能something()
在这里调用,你只能使用静态值。在某些时候,您必须在代码中以不同的方式设置这些值。
Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.
像任何其他 PHP 静态变量一样,静态属性只能使用文字或常量进行初始化;不允许使用表达式。因此,虽然您可以将静态属性初始化为整数或数组(例如),但您不能将其初始化为另一个变量、函数返回值或对象。
For example:
例如:
class Foo {
public static $bar = null;
public static function init() {
self::$bar = array(...);
}
}
Foo::init();
Or do it in __construct
if you're going to instantiate the class.
或者,__construct
如果您要实例化该类,请执行此操作。