魔术方法__set()和__get()

来源:互联网 发布:如何做网络写手 编辑:程序博客网 时间:2024/05/22 13:31
<?php   class person   {  private $name;  private $sex;  private $age;    function __construct($name="",$sex='男',$age=90)  {  $this->name=$name;  $this->sex=$sex;  $this->age=$age;  }  public function __set($nam,$val){  if($nam=="sex"){  if(!($val=='男'||$val=='女')){  return;  }  }  if($nam=="age"){  if($val>150||$val<0){  return;  }  }  $this->$nam=$val;  }  public function __get($n){  if($n=="sex"){  return "保密";  }  elseif($n=="age"){  if($this->age>40)     return $this->age-10;  else     return $this->$n;  }  else{  return $this->$n;  }  }  public function info()  {  echo"我的名字是:".$this->name."  性别:".$this->sex."  年龄:".$this->age."<br>";  }    function __destruct()  {  echo"再见".$this->name."<br>";  }  }  $person1=new person("张三",'男',80);  echo"姓名:",$person1->name."<br>";  echo"性别:",$person1->sex."<br>";  echo"年龄:",$person1->age."<br>";  echo$person1->info()."<br>";  $person1->name="李四";  $person1->sex='女';  $person1->age=60;  echo$person1->info()."<br>";  $person1->sex="保密";  $person1->age=600;  echo$person1->info()."<br>";?>