Public static variable value

时光怂恿深爱的人放手 提交于 2019-12-17 14:01:35

问题


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


回答1:


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.

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

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.



来源:https://stackoverflow.com/questions/6500732/public-static-variable-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!