有没有办法使用私有变量来声明其他私有变量?我的代码看起来像这样:
class MyClass{
private $myVar = "someText";
private $myOtherVar = "something" . $this->myVar . "else";
}
但这以PHP Fatal error: Constant expression contains invalid operations
与andoud $this->
有没有办法在php中执行此操作?
答案 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";
}
}