是否可以定义PHP类属性并使用同一类中的属性动态分配值?就像是:
class user {
public $firstname = "jing";
public $lastname = "ping";
public $balance = 10;
public $newCredit = 5;
public $fullname = $this->firstname.' '.$this->lastname;
public $totalBal = $this->balance+$this->newCredit;
function login() {
//some method goes here!
}
}
Run Code Online (Sandbox Code Playgroud)
产量:
解析错误:语法错误,第6行意外的'$ this'(T_VARIABLE)
上面的代码有什么问题吗?如果是这样,请指导我,如果不可能,那么实现这一目标的好方法是什么?
Riz*_*123 11
您可以将它放入构造函数中,如下所示:
public function __construct() {
$this->fullname = $this->firstname.' '.$this->lastname;
$this->totalBal = $this->balance+$this->newCredit;
}
Run Code Online (Sandbox Code Playgroud)
为什么你不能按照你想要的方式去做?手册中的引用解释了它:
此声明可能包括初始化,但此初始化必须是常量值 - 也就是说,它必须能够在编译时进行评估,并且必须不依赖于运行时信息才能进行评估.
有关OOP属性的更多信息,请参阅手册:http://php.net/manual/en/language.oop5.properties.php