Strange parse error with static concatenated string variable [closed]

泄露秘密 提交于 2020-01-03 13:31:14

问题


I'm getting this error:

Parse error: syntax error, unexpected '.', expecting ',' or ';' in /var/(...)/config.php on line 5

With this (simplified) code:

<?php

class Config
{
   public static $somevar = "Date: " . date('Y');
}

?>

I thought this was valid php, but I guess not... what am I doing wrong here? Thanks!


回答1:


According to the PHP docs:

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.

Try writing

Config::$somevar = "Date: " . date('Y');

after the class definition.




回答2:


No operation or function is allow for property initialization, because this is evaluated when parsing.




回答3:


From Manual

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.



来源:https://stackoverflow.com/questions/4267050/strange-parse-error-with-static-concatenated-string-variable

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