【问题标题】:Parse error: syntax error, unexpected '.', expecting ',' or ';' [closed]解析错误:语法错误,意外的 '.',期待 ',' 或 ';' [关闭]
【发布时间】:2012-06-13 17:20:52
【问题描述】:

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

public static $user_table = TABLE_PREFIX . 'users';

TABLE_PREFIX 是定义函数创建的常量

【问题讨论】:

标签: php


【解决方案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】:

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

    【讨论】:

      猜你喜欢
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      • 2012-07-15
      • 2012-07-04
      • 1970-01-01
      • 2021-11-05
      相关资源
      最近更新 更多