标签云

微信群

扫码加入我们

WeChat QR Code

Is it possible to define a PHP class property and assign the value dynamically using a property within the same class? Something like: 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!}}Yields:Parse error: syntax error, unexpected '$this' (T_VARIABLE) on line 6Is anything wrong in the above code? If so, please guide me and if it is not possible then what is a good way to accomplish this?


Yuvi At initialization in the class definition it has to be a constantvalue which can be evaluated at compile time; In the constructor or other functions you can assign what you want

2019年04月22日08分40秒

What if we want to access the dynamic property in a child class? How do you call it? I am facing challenge in that.

2019年04月22日08分40秒

andex As long as you don't overwrite the property in your child class you can just access it like this: $this->yourProperty

2019年04月22日08分40秒

Rizier thanks. It works now.

2019年04月22日08分40秒