PHP 中的静态函数变量和串联

发布于 2024-10-17 08:24:38 字数 420 浏览 2 评论 0原文

请考虑以下情况:

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心在旅行 2024-10-24 08:24:38

该手册在变量范围中指出:

尝试将值分配给这些作为表达式结果的[静态]变量将导致解析错误。

静态关键字中也提到了它:

与任何其他 PHP 静态变量一样,静态属性只能使用文字或常量进行初始化;不允许使用表达式。

尽管应该注意的是,无论是否静态,属性都不能使用表达式进行初始化。

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.

烟织青萝梦 2024-10-24 08:24:38

您不能在初始值设定项中执行表达式。但是,您可以这样做:

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

鲜为人知的事实是,即使初始值设定项不能包含运行时表达式,它也可以包含可以在运行时定义和解析的常量。不过,必须在首次使用 $var 时定义常量,否则您将得到与常量相同的字符串(例如 "FOOBAR")。

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

过期以后 2024-10-24 08:24:38

我这样做:

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();

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文