2012-03-09 176 views
2

Possible Duplicate:
Syntax error while defining an array as a property of a classPHP的静态变量初始化

我试图做到以下几点:

final class TestClass { 
    public static $myvar = 10*10; //line 3 
    //rest of code... 
} 

但我得到这个错误:syntax error, unexpected '*', expecting ',' or ';' [line 3]

为什么不是这可能吗?当然,如果我将10 * 10更改为100,则一切正常。 不允许用数学计算初始化一个静态变量吗?不可能以任何方式?

+1

另外,可以创建一个静态的getter函数:http://stackoverflow.com/a/7785213/1335996 – 2013-03-13 15:46:23

+0

从PHP 5.6开始,'static'允许使用标量表达式,因此您的问题中的代码完全可用PHP> = 5.6。一个标量表达式可能包括整数,浮点数,字符串和常量与数学,位,逻辑,连接,三元和比较运算符相结合。 例如,以下定义现在在您的课程内部是正确的: 'public static $ bar =“该课程名称是”.__ CLASS __;' 'public static $ baz = 8 >> 1;' 'public static $ bat = 10 + 3 * 2;' – 2017-02-19 20:09:59

回答

9

从PHP文档

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.

2

编号类属性(即使是静态的)只允许通过值初始化,而不是表达式。

2

不,这不可能在静态/非静态初始化做任何事情。你只能设置简单变量(protected $ _value = 10;)或构建数组(protected static $ _arrr = array(“key”=>“value”))。

在重新初始化类之前,您可以创建z初始化静态方法和$ _isInitialized静态字段,但必须以某种方式(在构造函数,相同工厂实现等中)调用Initialize方法。

5

我认为你必须在你的类中创建一个静态init方法是这样

final class TestClass { 
    public static $myvar = null; //line 3 

    public static function init() { 
    self::$myvar = 10*10; 
    } 
    //rest of code... 
} 

,并调用init第一喜欢这个

TestClass::init(); 

这就是静态路