Use private var in declaration of other private var in php

怎甘沉沦 提交于 2020-01-07 12:34:11

问题


Is there a way to use a private variable to declare an other private variable? My Code looks like this:

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

But this ends in a PHP Fatal error: Constant expression contains invalid operations

Tried it with and withoud $this->

Is there a way to do this in php?


回答1:


Default values for properties can't be based on other properties at compile-time. However, there are two alternatives.

Constant expressions

Constants can be used in default values:

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

As of PHP 7.1, such a constant could itself be private (private const).

Initialising in the constructor

Properties can be declared with no default value, and assigned a value in the class's constructor:

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

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


来源:https://stackoverflow.com/questions/40185018/use-private-var-in-declaration-of-other-private-var-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!