解析错误:语法错误、意外的“.”、预期的“、”或“;”[已关闭]

php
2022-08-30 22:07:22

这件事让我很烦恼。我收到解析错误:语法错误,意外的“.”,在此行中期望“,”或“;”

public static $user_table = TABLE_PREFIX . 'users';

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


答案 1

静态类属性在编译时初始化。初始化静态类属性时,不能使用常量与字符串文本连接,因为常量的值在运行时之前是未知的。相反,请在构造函数中初始化它: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

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

PHP >= 5.6 的更新

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

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


答案 2

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


推荐