在php中使用private var声明其他私有var

时间:2016-10-21 20:33:03

标签: php php-7

有没有办法使用私有变量来声明其他私有变量?我的代码看起来像这样:

class MyClass{
    private $myVar = "someText";
    private $myOtherVar = "something" . $this->myVar . "else";
}

但这以PHP Fatal error: Constant expression contains invalid operations

结尾

与andoud $this->

一起尝试

有没有办法在php中执行此操作?

1 个答案:

答案 0 :(得分:2)

属性的默认值不能在编译时基于其他属性。但是,有两种选择。

常量表达式

常量可以在默认值中使用:

class MyClass {
    const MY_CONST = "someText";
    private $myVar = self::MY_CONST;
    private $myOtherVar = "something" . self::MY_CONST . "else";
}

从PHP 7.1开始,这样的常量本身可以是私有的(private const)。

在构造函数中初始化

可以声明属性没有默认值,并在类的构造函数中赋值:

class MyClass {
    private $myVar = "someText";
    private $myOtherVar;

    public function __construct() {
        $this->myOtherVar = "something" . $this->myVar . "else";
    }
}