关于php:2022718-魔术方法之-set

魔术办法之 __set

一、__set

(一)调用机会

设置一个类的成员变量时调用。

(二)用处
  1. 用来在类的内部设置公有属性的值
  2. 给一个未定义的属性赋值。
(三)例子
<?php

class User{
    private $name;
    private $age;

    public function __set($property,$val){
        switch($property){
            case 'name':
                $this->name = $val;
                break;
            case 'age':
                $this->age = $val;
                break;
            default:
                $this->$property = $val;
                break;
        }
    }
    public function getProperty($property){
        return isset($this->$property) ? $this->$property : $property.' 属性不存在!'; 
    }
}

$user = new User();
$user->name = 'Moonshadow';
echo $user->getProperty('name')."\n";       // Moonshadow
echo $user->getProperty('weight')."\n";     // weight 属性不存在!
$user->weight = 'unknow';
echo $user->getProperty('weight');          // unknow

剖析:当给公有属性 name 赋值时,__set 办法被调用。

(四)留神

__set办法的参数有且只能是2个,一个是属性名,一个是属性要设置的值
多了少了都会报错。

二、参考资料

  1. 思否-PHP之十六个魔术办法详解

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理