Blogger Information
Blog 51
fans 3
comment 1
visits 36085
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
类、构造器、__get()、__set()—2018年5月3日9时32分
Gee的博客
Original
610 people have browsed it

类、构造器、__get()、__set()

实例

<?php


class Student
{
    private $name = '';
    private $sex = 0;
    private $age = 0;
    private $id = 0;
    private $grade = [];
    private $data = [];

    public function __construct($name, $sex, $age, $id, $grade)
    {
        $this->name = $name;
        $this->sex = $sex;
        $this->age = $age;
        $this->id = $id;
        $this->grade = $grade;
    }

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

运行实例 »

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

实例

<?php

require './class/Student.php';

$student1 = new Student('小明', 0, 18, 1234567, [95, 96, 88, 79]);

echo '姓名: ',$student1->name,'<br>';
echo '年龄: ',$student1->age,'<br>';
echo '学号: ',$student1->id,'<br>';
echo '成绩: <pre>',print_r($student1->grade, true),'<br>';

echo '身高: ',$student1->tall,'<br>';

$student1->tall = 180;

echo '身高: ',$student1->tall,'<br>';

运行实例 »

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

搜狗截图20180503093406.png

总结:

__get()、__set(): 魔术方法,可以访问和设置对象的私有属性

对于传入的属性,可以进行判断,如果有则输出,如果没有则可以进行设置,作为用户自定义属性添加进去


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