Blogger Information
Blog 18
fans 0
comment 0
visits 14872
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
php方法的重载__get()、__set()、 __isset()、 __unset()
牛粪也香的博客
Original
745 people have browsed it

1、私有属性或受保护的属性无法直接访问

image.png

2、__get()方法,通过这个方法,就可以直接调用

image.png

3、__set 方法:给已经存在的属性赋值,或添加新的属性

image.png

image.png

image.png

3、重载 属性的权限设置

image.png

image.png

attr_chongzai.php

<?phpnamespace _1102;class ClassName  { private $name; private $age; protected $girl_friend; public function __construct($name,$age) { $this->name= $name; $this->age= $age; } //属性重载的方法 //__get(),相当于一个自动方法,让用户访问 私有或受保护的 属性 public function __get($name) { return $this->$name; } //__set重载对属性赋值 // __set($name,$value) public function __set($p_name,$p_value) { // $this->$p_name=$p_value; if($p_name=='what') { return $this->name=="老余" ?  $this->$p_name='you can change your girl_friend'.$p_value : $this->$p_name="no power"; }else{ $this->$p_name=$p_value; } } public function __isset($name)//检测是否存在某个属性 { return isset($this->$name); } public function __unset($name)//销毁存在的某个属性 { unset($this->$name); }
}$obj= new ClassName('老余',"19.2");$obj->what="另一个";echo $obj->what;//调用的属性what和值老余都相等echo "<hr>";
$obj1= new ClassName('老余2',"19.2");$obj1->what="另一个";echo $obj1->what;//调用的属性相等但值不等echo "<hr>";
$obj2= new ClassName('老余3',"19.2");$obj2->what1="what1";echo $obj2->what1;//调用的属性和值都不等echo "<hr>";
$obj->girl_friend='你懂的';//这里相当于给girl_firend赋值   girl_friend = __set函数的 $P_name// '你懂的'  =  __set函数的 $P_valueecho $obj->girl_friend;echo "<hr>";$obj->firt_girl='你不懂';//新添加一个属性echo $obj->firt_girl;echo "<hr>";
echo "<hr>";echo isset($obj->firt_girl) ? "yes":"no";//存在显示yesecho "<hr>";echo isset($obj->name1) ? "yes":"no";//不存在显示NOecho "<hr>";echo $obj->age;//原有属性unset($obj->age);//销毁某个属性echo $obj->age;//查看报错echo $obj->name;

Correction status:qualified

Teacher's comments:合格
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post