Static Function Variables and Concatenation in PHP

自作多情 提交于 2019-11-28 07:00:47

问题


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?


回答1:


The manual states, in Variables scope:

Trying to assign values to these [static] variables which are the result of expressions will cause a parse error.

There is also mention of it in Static keyword:

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed.

Although it should be noted that a property, static or not, cannot be initialized using an expression neither.




回答2:


You can not do expressions in initializers. You can, however, do this:

define('FOOBAR', 'foo'.'bar');
static $var = FOOBAR;
echo $var;

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




回答3:


I do this:

class MyClass {

  static $var1;
  static $var2;
  public static function _init() {
      self::$var1 = 'slkslk' . 'sksks' . 'arbitrary' ; 
      self::var2 = <<<EOT
          <root>
            <elem1>skjsksj</elem1>
          </root>
EOT;
  }
}
MyClass::_init();


来源:https://stackoverflow.com/questions/4976717/static-function-variables-and-concatenation-in-php

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