跳转到主内容
websoft网络软件专家 - 深耕网络技术,打造实用软件!

$this->$propertyName = $value,$this->propertyName = $value的区别?

在通过__set($propertyname,$value)设置private成员属性时, 用$this->$propertyname = $value的写法才可以进行private变量值的修改, 采用$this->propertyname = $value的写法则不能进行变量值的修改。 完整代码: PHP 8.5.5 PHP 8.5.5 是 PHP 8.5 分支的维护更新版本。该版本延续了“小步快跑”的迭代逻辑,通过深度错误修复、底层性能微调以及安全加固,旨在为开发者提供一个更健壮、更高效的运行环境。该版本严格遵守语义化版本规范,不包含破坏性变更。 下载 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 "
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 "
name:".($this->name)."
age:".($this->age)."
average".($this->average); }
} 回复内容: 在通过__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 "
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 "
name:".($this->name)."
age:".($this->age)."
average".($this->average); }
}
$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这个属性
楼主,
$this->$propertyName = $value
这样的赋值是
$this
实例中变量为
$propertyName
变量的值,此处的
$propertyName
仍然是个变量,而
$this->propertyName
就是$this的属性了; 前者的情况是这样的,例如
$propertyName = 'enable'
; 那么
$this->$propertyName
就等同与
$this->enable
;

相关文章