跟大家講解下有關$this->$propertyName = $value,$this->propertyName = $value的區別?,相信小伙伴們對這個話題應該也很關注吧,現在就為小伙伴們說說$this->$propertyName = $value,$this->propertyName = $value的區別?,小編也收集到了有關$this->$propertyName = $value,$this->propertyName = $value的區別?的相關資料,希望大家看到了會喜歡。
在通過__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 $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 $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;
來源:php中文網