1

为什么我不能在类内的变量中使用分隔符 (.)?

class Object(){
    public $var  = "Hello"."World";
    # Or
    public $test = "Hello";
    public $var2 = $this->test."World";
}

这段代码给了我这个错误:

解析错误:语法错误,意外的 '.',期待 ',' 或 ';' 在第 2 行的 test.php 中

我该怎么做?

4

1 回答 1

4

因为你不能用变量表达式声明类属性。这意味着您不能使用任何算术运算符+ - * /或连接运算符.,也不能调用函数。在你的三行中,只有$test应该工作;另外两个会给你错误。

如果您需要动态构建字符串,请在构造函数中进行。

class Object {
    public $test = "Hello";
    public $var2;

    public function __construct() {
        $this->var2 = $this->test . "World";
    }
}

顺便说一句,.不是“字符串分隔符”。它是连接运算符。你用它来连接字符串,而不是分开它们。

于 2011-01-22T17:32:03.210 回答