Blogger Information
Blog 15
fans 0
comment 1
visits 10863
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
对象创建和魔术方法----5.2
吴明的博客
Original
728 people have browsed it

总结:  类是对象的模板,对象是类的实例

类中的属性一般定义为私有属性,单独创镌读取和修改方法--- 魔术方法 。一切都是为了安全考虑。


类文件,注意的有命名,后面的命名空间,属性以及方法的属性(私有,保护,公共)retun 不超过一个。

实例
<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/2
 * Time: 23:40
 */
class GirlFriendClass
{
//声明属性
private $name;
private $age;
private $stature;
private $data=[];
// 构造方法
public function __construct($name='',$age=0,$stature=[])
{
    $this->name = $name;
    $this->age = $age;
    $this->stature = $stature;
}
    //魔术方法: 查询器
    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;
        }
    }

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

调用的

实例

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/2
 * Time: 23:31
 */
header('Content-type:text/html;charset=utf8');
require'lib/GirlFriendClass.php';
$girlfriend = new GirlFriendClass('浩浩',23,[34,30,90]);
//测试魔术方法_get()
echo '姓名:'.$girlfriend->name.'<br>';
echo '年龄:'.$girlfriend->age.'<br>';
echo '三维:'.var_dump($girlfriend->stature,true).'<br>';
//获取不存在的属性
echo '爱好:'.$girlfriend->hobby.'<br>';
echo'<hr>';
//测试魔术方法__set();
$girlfriend->name = '范冰冰';
$girlfriend->age = 35;
$girlfriend->stature = [35,85,98];
echo '姓名: ',$girlfriend->name,'<br>';
echo '年龄: ',$girlfriend->age, '<br>';
echo '三维: ', print_r($girlfriend->stature,true), '<br>';
$girlfriend->hobby = '舞蹈';
echo '爱好:'.$girlfriend->hobby.'<br>';

运行实例 »

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


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