Let's talk about the design mode-before the value object mode, you need to understand the value transfer and reference transfer: 1. value Object mode concept: if you assign the same object resource to two different variables and change one of them, the other variables will not be affected. This is the purpose of using the value object mode. Check
Let's talk about the design mode-before the value object mode, you need to understand the value transfer and reference transfer:
1. concept of value object mode:
If you assign the same object resource to two different variables, and then change one of the variables, the other variables remain unaffected. This is the purpose of using the value object mode.
Take the following example:
amount = (float)$amount; } public function getAmount() { return $this->amount; } public function add($dollar) { $this->amount += $dollar->getAmount(); }} class Work { protected $salary; public function __construct() { $this->salary = new BadDollar(200); } public function payDay() { return $this->salary; } } class Person { public $wallet;} $job = new Work;$p1 = new Person;$p2 = new Person;$p1->wallet = $job->payDay();print_r($p1->wallet->getAmount()); //200$p2->wallet = $job->payDay();print_r($p2->wallet->getAmount()); //200$p1->wallet->add($job->payDay());print_r($p1->wallet->getAmount()); //400//this is bad — actually 400print_r($p2->wallet->getAmount()); //400//this is really bad — actually 400print_r($job->payDay()->getAmount()); //400
Looking at the above example, we can see that the obvious error is that $ p1 and $ p2 use the same BadDollar object. First, the instance of class Work and class Person has been created. Assume that each employee initially has an empty e-wallet. the employee's e-wallet Person: wallet is assigned a value through the object resource variable returned by the Work: payDay () function, so it is set as an object instance of the BadDollar class. In fact, $ job: salary, $ p1: wallet, and $ p2: wallet point to instances of the same object.
In the value object mode, redesign the Dollar object as follows:
class Dollar { protected $amount; public function __construct($amount=0) { $this->amount = (float)$amount; } public function getAmount() { return $this->amount; } public function add($dollar) { return new Dollar($this->amount + $dollar->getAmount()); }}
As you can see, the main change is in the Dollar: add () function, which creates and returns a new Dollar instance. Therefore, although you specify the current object to multiple variables, however, every variable change does not affect other variable instances.
Value Object mode design note:
1. the attribute of the protected value object cannot be accessed directly.
2. assign values to attributes in the constructor.
3. remove any method function (setter) that will change the attribute value. Otherwise, the attribute value is easily changed.