2011-06-28 241 views
5

我想声明一个公共静态变量是阵列的阵列:公共静态变量值

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 ... 
} 

但我得到一个错误:

Parse error: parse error, expecting `')'' in ...

+0

什么是'something()'?此外,这是声明为一个类属性('公共静态$上下文)或方法的某处? – deceze

+0

这是一个正常的功能..它是在课堂外宣布的。该变量被声明为类属性 – Alex

+0

“在类之外声明”?我们可以看到这段代码和其他课程在一起吗? – BoltClock

回答

9

你不能使用表达式当声明类属性时。即您不能在这里拨打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.

http://www.php.net/manual/en/language.oop5.static.php

例如:

class Foo { 
    public static $bar = null; 

    public static function init() { 
     self::$bar = array(...); 
    } 
} 

Foo::init(); 

或做它__construct,如果你打算将类实例。

+0

这很奇怪,因为我可以声明一个公共静态函数,它将返回我的数组,它将是相同的 – Alex

+1

在解析源代码时创建类属性的初始值。此时,需要为那些初始类值保留内存,因为它们需要存储在某个地方。这发生在代码实际执行之前。你不能为函数的返回值保留内存,因为函数可能会返回任何东西。而且由于解析还没有完成,功能还不能执行。因此,在解析代码时,只允许已知大小的静态值。稍后在运行时(明确)调用一个函数,并可能返回任何内容。 – deceze