__set() 方法

class person{

    public $name;
    private $weight;
    protected $age;

    public function __construct($name,$weight,$age){
        $this->name = $name;
        $this->weight = $weight;
        $this->age = $age;
    }

    /*
    public function set($name,$value){ // 此处的$name 和属性$name 不同注意理解区分
        $this->$name = $value; // 注意$this->$name 中的$name的意义
        return $this->$name;
    }
    */

    # 自动调用 无需手工书写如$p->set($varName,$varVaule) 
    public function __set($name,$vaule){ 
         
        $this->$name = $vaule;
    }
    

    public function property(){
        echo "The weight for {$this->name}  is {$this->weight} kg , his age is {$this->age} years old " ;
    }

}

$bushou = new person('bushou',87,28);

/* 
# 手工调用set()方法
$bushou->set('weight',60);
$bushou->set('age',18);
var_dump($bushou); // 对象赋值之后,并不能使用$this->age或者$this->weight直接取到数据
*/

# 自动触发__set()方法
$bushou->weight = 60;
$bushou->age = 19;
var_dump($bushou);

以上代码运行后会输出:

object(person)#1 (3) {
["name"]=> string(6) "bushou"
["weight":"person":private]=> int(60)
["age":protected]=> int(19)
}

标签: php, OOP

分享到: