在PHP中声明默认类属性时不能使用连接


Cannot use concatenation when declaring default class properties in PHP?

在PHP类中声明属性的默认值时,似乎不能使用连接。这有什么原因吗?

class Foo
{
    public $property = __DIR__ . '/';
}

5.6之前的PHP版本

见http://www.php.net/manual/en/language.oop5.properties.php

通过使用关键字public、protected或private之一,后跟一个普通的变量声明来定义它们。该声明可以包含一个初始化,但该初始化必须是一个常数值——也就是说,它必须能够在编译时求值,并且不能依赖于运行时信息才能求值。

对于更复杂的初始化,使用构造函数
public function __construct()
{
    $this->settings = __DIR__ . '/';
}

PHP 5.6及以上版本

从PHP 5.6版本开始,在PHP中声明默认的类属性时可以使用连接。参见https://wiki.php.net/rfc/constrongcalar_exprs。

这允许只能接受静态值的地方(const声明、属性声明、函数参数等)也可以接受静态表达式。

您需要在__constructor中进行所有初始化。即在php5中。或者在旧php4的$this->class_name()中。