在通过__set($propertyName,$value)设置private成员属性时,
用$this->$propertyName = $value的写法才可以进行private变量值的修改,
采用$this->propertyName = $value的写法则不能进行变量值的修改。
完整代码:
class BasePerson{
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);
}
}