PHP parse error while creating closures on a Class static variable
我正在使用5.3.10并尝试按照以下方式创建闭包,但它给出了解析错误。有人能告诉我为什么会出现解析错误吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class ABC { public static $funcs = array( 'world' => function() { echo"Hello,"; echo"World! "; }, 'universe' => function() { echo"Hello,"; echo"Universe! "; }, ); } |
这不起作用的原因是,在PHP中,不允许直接将闭包赋给(静态)类变量初始值设定项。
因此,要使代码正常工作,您必须使用此变通方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php class ABC { public static $funcs; } ABC::$funcs = array( 'world' => function() { echo"Hello,"; echo"World! "; }, 'universe' => function() { echo"Hello,"; echo"Universe! "; }, ); $func = ABC::$funcs['world']; $func(); |
解决方法来自于对堆栈溢出问题的回答:php:如何初始化静态变量
顺便说一句,注意也不可能通过
静态属性只能使用文本或常量初始化。从http://php.net/manual/en/language.oop5.static.php上的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.