问题
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