Blogger Information
Blog 42
fans 4
comment 0
visits 30878
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
5.3 类的创建及get/set魔术方法 --30Day
小丑的博客
Original
716 people have browsed it

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

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