博客列表 >5.3 类的创建及get/set魔术方法 --30Day

5.3 类的创建及get/set魔术方法 --30Day

小丑的博客
小丑的博客原创
2018年05月03日 13:42:17706浏览

PerInfo 类

实例

<?php


class PerInfo {

    //设置私有属性
    private $userName='';
    private $age = 0;
    private $address = '';
    private $iphone = '';


    //构造方法
    public function __construct($userName='Smart',$age,$address='',$iphone=''){

        $this->userName = $userName;
        $this->age = $age;
        $this->address = $address;
        $this->iphone = $iphone;

    }

//    public function getUserName(){
//        return $this->userName;
//    }



//    魔术方法set,判断如果属性值等于age,进行赋值
    public function __set($name,$value){
        if($name == 'age' ){
            $this->$name = $value;
        }else{
            echo '赋值错误';
        }
    }


//    魔术方法get,判断属性值是否存在及判断条件
    public function __get($name)
    {
        $msg = '';
        if(!isset($this->$name)){
            $msg = "{$name} 属性值不存在";
        }else if($name == 'age' && $this->$name >=10){
            $msg =  $this->$name;
        }else{
            $msg = '年龄超出设定范围不存在';
        }
        return $msg;
    }





}

运行实例 »

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

类的实例化及属性引用

实例

<?php


require 'PerInfo.php';


$per = new PerInfo('PHP',8,'www','www');

//echo $per->getUserName();

//不存在属性值 username
$per->username = '1';
echo '<br>';

//agea 属性值不存在
echo $per->agea;


$per->age = '19';
echo '<br>';
echo $per->age;

运行实例 »

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

微信图片_20180503134148.png

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议