php 解析错误:语法错误,意外的“.”,期待“,”或“;”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10969342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:29:30  来源:igfitidea点击:

Parse error: syntax error, unexpected '.', expecting ',' or ';'

php

提问by Tejas Jadhav

This thing is bugging me a lot. I'm getting Parse error: syntax error, unexpected '.', expecting ',' or ';' at this line

这件事让我很烦恼。我收到解析错误:语法错误,意外的 '.',期待 ',' 或 ';' 在这一行

public static $user_table = TABLE_PREFIX . 'users';

TABLE_PREFIX is a constant created by define function

TABLE_PREFIX 是由定义函数创建的常量

回答by Michael Berkowski

Static class properties are initialized at compile time. You cannot use a constant TABLE_PREFIXto concatenate with a string literal when initializing a static class property, since the constant's value is not known until runtime. Instead, initialize it in the constructor:

静态类属性在编译时初始化。TABLE_PREFIX初始化静态类属性时,不能使用常量与字符串文字连接,因为常量的值直到运行时才知道。相反,在构造函数中初始化它:

public static $user_table;

// Initialize it in the constructor 
public function __construct() {
  self::$user_table = TABLE_PREFIX . 'users';
}

// If you only plan to use it in static context rather than instance context 
// (won't call a constructor) initialize it in a static function instead 
public static function init() {
  self::$user_table = TABLE_PREFIX . 'users';
}

http://us2.php.net/manual/en/language.oop5.static.php

http://us2.php.net/manual/en/language.oop5.static.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.

像任何其他 PHP 静态变量一样,静态属性只能使用文字或常量进行初始化;不允许使用表达式。因此,虽然您可以将静态属性初始化为整数或数组(例如),但您不能将其初始化为另一个变量、函数返回值或对象。

Update for PHP >= 5.6

更新 PHP >= 5.6

PHP 5.6 brought limited support for expressions:

PHP 5.6 对表达式的支持有限:

In PHP 5.6 and later, the same rules apply as const expressions: some limited expressions are possible, provided they can be evaluated at compile time.

在 PHP 5.6 及更高版本中,适用于 const 表达式的相同规则:一些有限的表达式是可能的,前提是它们可以在编译时计算。

回答by troelskn

The dot is a string concatenation operator. It's a runtime function, so it can't be used to declare a static (parsetime) value.

点是字符串连接运算符。它是一个运行时函数,因此不能用于声明静态(解析时间)值。