When setting private member attributes through __set($propertyName,$value),
use $this->$propertyName = $value to modify the private variable value,
use $ The writing rule of this->propertyName = $value cannot modify the variable value.
Full code:
class BasePerson{
<code> private $name; private $age; private $average; function __construct(){ $num_args = func_num_args(); if($num_args == 1){ $this->name = func_get_arg(0); } elseif($num_args == 2){ $this->name = func_get_arg(0); $this->age = func_get_arg(1); } elseif($num_args == 3){ $this->name = func_get_arg(0); $this->age = func_get_arg(1); $this->average = func_get_arg(2); } } private function __set($propertyName,$propertyValue){ echo "</br>BasePerson __set()"; if($propertyName == "name"){ if($propertyValue == "zhangsan" || $propertyValue == "wangwu"){ $this->$propertyName = $propertyValue; } } elseif($propertyName=="age"){ if($propertyValue >150 || $propertyValue <0){ return ; } } $this->$propertyName = $propertyValue; } function __toString(){ return "</br>name:".($this->name)."</br>age:".($this->age)."</br>average".($this->average); } </code>
}
When setting private member attributes through __set($propertyName,$value),
use $this->$propertyName = $value to modify the private variable value,
use $ The writing rule of this->propertyName = $value cannot modify the variable value.
Full code:
class BasePerson{
<code> private $name; private $age; private $average; function __construct(){ $num_args = func_num_args(); if($num_args == 1){ $this->name = func_get_arg(0); } elseif($num_args == 2){ $this->name = func_get_arg(0); $this->age = func_get_arg(1); } elseif($num_args == 3){ $this->name = func_get_arg(0); $this->age = func_get_arg(1); $this->average = func_get_arg(2); } } private function __set($propertyName,$propertyValue){ echo "</br>BasePerson __set()"; if($propertyName == "name"){ if($propertyValue == "zhangsan" || $propertyValue == "wangwu"){ $this->$propertyName = $propertyValue; } } elseif($propertyName=="age"){ if($propertyValue >150 || $propertyValue <0){ return ; } } $this->$propertyName = $propertyValue; } function __toString(){ return "</br>name:".($this->name)."</br>age:".($this->age)."</br>average".($this->average); } </code>
}
<code>$name = 'test'; $$name = '123'; var_dump($test); //输出123 //希望你能理解 //同理 $this->$proertyName //需要看$proertyName的值, 是设置$proertyName的值这个属性 $proertyName = 'age'; $this->$proertyName = '12'; var_dump($this->age); //输出12 $this->proertyName //设置的是proertyName这个属性</code>
Original author, $this->$propertyName = $value
Such an assignment is that the variable in the $this
instance is the value of the $propertyName
variable. The $propertyName
here is still a variable, and $this->propertyName
is the attribute of $this;
The former situation is like this, for example, $propertyName = 'enable'
;
then $this->$propertyName
is equivalent to $this->enable
;