Blogger Information
Blog 26
fans 0
comment 0
visits 16503
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
构造方法创建类
瘦不下来的博客
Original
685 people have browsed it
创建类:

实例

<?php

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;
        }
        
    }

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post