Blogger Information
Blog 64
fans 2
comment 3
visits 75703
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
创建类,使用魔术查询__get()及魔术方法设置__set()—2018年5月3日09:27:45
清雨的博客
Original
633 people have browsed it


类文件:

./class/Admin.php

实例

<?php

/**
 * Created by PhpStorm.
 * User: 清雨
 * Date: 2018/5/3
 * Time: 8:50
 */
class Admin
{
    private $name;
    private $age;
    public function __construct($name,$age)
    {
        $this -> name = $name;
        $this -> age  = $age;
    }
    public function __get($name)
    {
        $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)
    {
        if (isset($this ->$name)){
            $this -> $name = $value;
        } else {
            $this->data[$name] = $value;
        }
    }
}

运行实例 »

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

index.php

实例

<?php
/**
 * Created by PhpStorm.
 * User: 清雨
 * Date: 2018/5/3
 * Time: 9:12
 */
require './class/Admin.php';
$admin = new admin('张无忌',31);
echo '姓名:',$admin ->name.'<br>';
echo '年龄:',$admin ->age;
echo '<hr>';
$admin -> name = '金毛狮王';
$admin -> age  = 60;
echo '姓名:',$admin ->name.'<br>';
echo '年龄:',$admin ->age;

运行实例 »

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

效果图:

12.png

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