魔术方法__set:

 触发时机:在类的外部对私有的成员属性进行赋值的时候自动调用

 参数:需要传入两个参数:第一个为成员属性名,第二个为成员属性值。

 注意:请对__get __set __isset __unset不要使用private关键词来声明这些魔术成员方法。

 ps(在5.3以前版本可以使用private,在5.3x版本之后全部都只允许public关键词,要么就不加)。

 
  
 
  
  1. <?php 
  2.  /**** 
  3.   * 
  4.   * __set魔术方法 
  5.   * 
  6.   */ 
  7.   class person { 
  8.     private $name,$sex,$age,$hf
  9.  
  10.     function __construct($name,$sex,$age,$hf){ 
  11.        $this->name=$name
  12.        $this->sex=$sex
  13.        $this->age=$age
  14.        $this->hf=$hf
  15.     } 
  16.  
  17.     function say(){ 
  18.       echo '你好我的名字叫'.$this->name.'我的性别是'.$this->sex.'我的年龄是'.$this->age.'我的婚否状态'.$this->hf; 
  19.     } 
  20.     //对私有属性赋值的时候自动该方法 
  21.     function __set($a,$v){ 
  22.         if($a=='hf'){ 
  23.         $this->$a=$v
  24.         } 
  25.        
  26.     } 
  27.   } 
  28. $p=new person('你好','男',19,'已婚'); 
  29.  
  30. //对私有属性进行赋值 
  31. $p->hf='未婚'
  32. $p->say(); 
  33. ?> 

 魔术方法__get:

 触发时机:在类外部调用一个私有属性的时候自动执行;

 参数:传一个参数即可,因为get只需要获得属性值即可,所以需要传入属性名。

 注意:值需要return回去  不要用echo输出

 
  
  1. <?php 
  2.  /**** 
  3.   * 
  4.   * __get魔术方法
  5.   * 
  6.   */ 
  7.   class person { 
  8.     private $name,$sex,$age,$hf
  9.  
  10.     function __construct($name,$sex,$age,$hf){ 
  11.        $this->name=$name
  12.        $this->sex=$sex
  13.        $this->age=$age
  14.        $this->hf=$hf
  15.     } 
  16.  
  17.     function say(){ 
  18.       echo '你好我的名字叫'.$this->name.'我的性别是'.$this->sex.'我的年龄是'.$this->age.'我的婚否状态'.$this->hf; 
  19.     } 
  20.   
  21.   //在类外部获取成员属性的时候自动触发 
  22.     function __get($v){ 
  23.      if($v=='sex'){ 
  24.        return $this->$v
  25.      } 
  26.     } 
  27.   } 
  28. $p=new person('你好','男',19,'已婚'); 
  29.  
  30.   
  31. // 调用私有方法sex  get方法获取到return返回来 接着输出 
  32. echo $p->sex; 
  33.  ?>