Blogger Information
Blog 42
fans 3
comment 2
visits 40513
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
类的创建及get/set魔术方法
虞者自愚的博客
Original
689 people have browsed it

创建类

实例

<?php

class Kaoshi {
    //声明属性
    private $name;
    private $zongfen;
    private $fenshu;
    private $data=[];

    //构造方法

    public function __construct($name='',$zongfen=0,array $fenshu=[])
    {
        $this->name =  $name;
        $this->zongfen = $zongfen;
        $this->fenshu = $fenshu;

    }

    //魔术方法:查询器

    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 {
            //如果属性不存在,则创建它并保存到类属性$data数组中
            $this->data[$name] = $value;
        }

    }

}

运行实例 »

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


类的实例化及属性引用

实例

<meta charset=utf-8>
<meta name=description content="">
<meta name=viewport content="width=device-width, initial-scale=1">
<?php

include 'class/KaoShi.php';

$kaoshi = new Kaoshi('苏三',843,[95,91,92,95,94,98,96,90,92]);

//测试魔术方法__get()

echo '姓名: ',$kaoshi->name,'<br>';
echo '总分: ',$kaoshi->zongfen, '<br>';
echo '各科分数: ', print_r($kaoshi->fenshu,true), '<br>';
// //获取不存在的属性
echo '平均分:', $kaoshi->pjf, '<br>';

echo '<hr>';

//测试魔术方法: __set()
$kaoshi->name = '李四';
$kaoshi->zongfen = 843;
$kaoshi->fenshu = [95,91,92,95,94,98,96,90,92];
echo '姓名: ',$kaoshi->name,'<br>';
echo '总分: ',$kaoshi->zongfen, '<br>';
echo '各科分数: ', print_r($kaoshi->fenshu,true), '<br>';
echo '<hr>';
echo '下面是自定义新创建的属性';
$kaoshi->pjf = 93.67;
echo '平均分: ',$kaoshi->pjf, '<br>';

$kaoshi->sex = 1;
$kaoshi->mobile = 13988888888;

// echo '性别:',$kaoshi->sex,'<br>';
echo '性别:'.($kaoshi->sex?'男':'女').'<br>';
echo '手机号码:',$kaoshi->mobile;

运行实例 »

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

TIM截图20180504091558.png

Correction status:Uncorrected

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