-1

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?

fuzzi
  • 87
  • 8
  • 7
    Answer, no. Do it in the constructor. Same with all class vars private or not. – AbraCadaver Oct 21 '16 at 20:34
  • 2
    **NOT** possible. You cannot initialize class variables with any expression that isn't resolvable at compile-time, and even that compile-time expression support is only available in newer PHP versions. earlier versions could not use expressions, period. – Marc B Oct 21 '16 at 20:37
  • http://stackoverflow.com/questions/37988721/string-concatenation-with-constants/37988890 – David Rojo Oct 21 '16 at 23:14

1 Answers1

2

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";
    }
}
Andrea
  • 19,134
  • 4
  • 43
  • 65