Home  >  Article  >  php magic method

php magic method

无忌哥哥
无忌哥哥Original
2018-06-28 14:26:112081browse

* 1. Magic methods: __get(), __set() to implement attribute queryers and setters

* 2. Magic methods have been introduced before and need to be triggered by specific scenarios and automatically called by the object

* 3.__get($name): Automatically triggered when the object's private attributes or non-existent attributes are obtained externally through the object

* 4.__set($name,$value): Externally set private Automatically triggered when an attribute or attribute value does not exist

* 5. The magic method can be applied to all existing or non-existing class attributes, and there is no need to create a corresponding access interface for each attribute

class GirlFriend3 {
    //声明属性
    private $name;
    private $age;
    private $stature;
    private $data=[];
    
    //构造方法
    public function __construct($name='',$age=0,array $stature=[]) 
    {
        $this->name = $name;
        $this->age = $age;
        $this->stature = $stature;
    }
    
    //魔术方法:查询器
    public function __get($name)
    {
//        return $this->$name;
        //加入检测:访问不存在的属性时给出提示信息
//        return isset($this->$name)?$this->$name:'无此属性';
        
        //如果类中添加一个自定义的数据收集器$data,就从这里取值
        $msg = null;
        if (isset($this->$name)) {
            $msg = $this->$name;
        } elseif (isset($this->data[$name])) {
            $msg = $this->data[$name];
        
        } else {
            $msg = '无此属性';
        }
        
        return $msg;
    }
    
    //魔术方法:设置器
    public function __set($name, $value)
    {
        //不做检测直接设置
//        $this->$name = $value;
        
        //完善设置器,实现对不存在属性的创建
        //如果访问的是已存在的属性,则直接输出
        if (isset($this->$name)) {
            $this->$name = $value; //输出属性
        } else {
            //如果属性不存在,则创建它并保存到类属性$data数组中
            $this->data[$name] = $value;
        }
    }
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn