PHP 中的静态函数变量和串联
请考虑以下情况:
$var = 'foo' . 'bar'; # Not a member of a class, free-standing or in a function.
但是,一旦我将 $var
标记为 static
:
static $var = 'foo' . 'bar';
PHP(WAMP 设置上的 5.3.1)就会抱怨以下错误:
解析错误:语法错误、意外的“.”、期望“,”或“;”
看来字符串连接是这里的罪魁祸首。
这是怎么回事?有人可以向我解释静态变量的规则吗?
Consider the following:
$var = 'foo' . 'bar'; # Not a member of a class, free-standing or in a function.
As soon as I mark $var
as static
, however:
static $var = 'foo' . 'bar';
PHP (5.3.1 on a WAMP setup) complains with the following error:
Parse error: syntax error, unexpected '.', expecting ',' or ';'
It seems that the string concatenation is the culprit here.
What's going on here? Can someone explain the rules for static variables to me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该手册在变量范围中指出:
静态关键字中也提到了它:
尽管应该注意的是,无论是否静态,属性都不能使用表达式进行初始化。
The manual states, in Variables scope:
There is also mention of it in Static keyword:
Although it should be noted that a property, static or not, cannot be initialized using an expression neither.
您不能在初始值设定项中执行表达式。但是,您可以这样做:
鲜为人知的事实是,即使初始值设定项不能包含运行时表达式,它也可以包含可以在运行时定义和解析的常量。不过,必须在首次使用
$var
时定义常量,否则您将得到与常量相同的字符串(例如"FOOBAR"
)。You can not do expressions in initializers. You can, however, do this:
Little known fact is that even though initializers can not contain runtime expressions, it can contain constants which can be defined and resolved at runtime. The constant has to be defined by the time
$var
is first used though, otherwise you'll get string identical to the constant (e.g."FOOBAR"
).我这样做:
I do this: