Dynamic Class Property Value Assignment in PHP
Defining class properties with constant values is the standard approach in PHP. However, in certain scenarios, it may be necessary to assign values dynamically.
Example:
Consider the following code:
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; }
This code attempts to assign the fullname and totalBal properties dynamically based on the values of other properties. However, it results in a parse error due to the use of $this within class-level properties.
Solution:
To dynamically assign class property values, place the assignment code within the class constructor. For example:
class user { private $firstname; private $lastname; private $balance; private $newCredit; private $fullname; private $totalBal; public function __construct() { $this->firstname = "jing"; $this->lastname = "ping"; $this->balance = 10; $this->newCredit = 5; $this->fullname = $this->firstname.' '.$this->lastname; $this->totalBal = $this->balance+$this->newCredit; } }
Explanation:
Class properties cannot be assigned dynamic values during declaration. According to PHP's manual, initialization must be a constant value evaluated at compile time. By using the constructor, the values can be assigned dynamically at object creation.
The above is the detailed content of How Can I Dynamically Assign Values to Class Properties in PHP?. For more information, please follow other related articles on the PHP Chinese website!