<?php
class Person{
    private $name;
    private $sex;
    private $age;
    function __construct($name="wj",$sex="男",$age=0){
        $this->name=$name;
        $this->sex=$sex;
        $this->age=$age;
    }
        function __get($names){
        if($names=="sex"){
            return "保密";
        }else if($names=="age"){
            if($this->age>30)
                return ($this->age-10);
            else
                return $this->$names;
        }
        else{
             return $this->$names;
        }   }
    function __isset($nam){
        if($nam=="name")
            return false;
        return isset($this->$nam);
    }
    function __unset($pnam){
        if($pnam=="name")
            return;
        unset($this->$pnam);
    }    public function say(){
        echo "姓名:".$this->name."<br>性别:".$this->sex."<br>年龄:".$this->age."<br>";
    }
}
    $p=new Person();
  
    $p->say();
   
    var_dump(isset($p->name));
    var_dump(isset($p->sex));
    var_dump(isset($p->age));
    
    unset($p->name);
    unset($p->sex);
    unset($p->age);
    
    $p->say();//结果:(姓名:wj 性别:保密 年龄:)为什么性别后面还有值,应该和年龄一样为空的啊,怎么回事?php

解决方案 »

  1.   

    __get()和__unset()你就不要使用了。通常没有必要使用这个。代之以写在别的方法里面就行了。
      

  2.   

    测试了下,
    首先3个unset()没有意义,因为你销毁的是__get()设置的方法,如果没有__get()你是不能销毁3个私有保护属性的,所以实际销毁工作都有__unset()来完成。
    但是你__unset()里面并没有销毁name,实际上你的sex,和age都已经被销毁了。
    之所以还存在 性别:保密 年龄:  是因为你在__get()里面的返回值,而$this->age>30的写法是有错误的,因为这个属性已经不存在了。
    好像说的有点乱