Blogger Information
Blog 32
fans 1
comment 0
visits 29001
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
__set(),__get(),魔术方法的使用
艾克的博客
Original
803 people have browsed it
<?php
/*
 * 魔术方法
 * 1.__construct(),构造方法必须以双下划线开头
 * 2.魔术方法不是由用户调用,由系统自动调用
 * 3.一般来说,魔术方法都是在用户进行非法操作的时候自动调用
 *
 * __get():当用户访问一个不存在或无权限访问的属性的时候自动调用
 * __set():当用户对一个不存在或者无权限访问的属性进行赋值的时候自动调用
 */
class Dome
{
    private $name = 'petert';
    protected $age = 30;
    //构造器
//    public function __construct($name,$age)
//    {
//        $this->name = $name;
//        $this->age = $age;
//    }

//用__get()来过滤非法访问
    public function __get($proname)//$proname是属性名称

    {

        if ($this->name == 'peter')
        {
            return $this->$proname;
        }else {
            echo '无权访问'.$this->name.'';
        }
    }

    public function __set($proname, $provalue)//__set()对当前属性输入的值 进行过滤
    {
        if ($proname == 'age') {//判断当前年龄是不是合法值
            if ($provalue > 18 && $provalue < 120) {
                $this->$proname = $provalue;
            }else {
                echo ''.$provalue.'非法数据';
            }
        }
        $this->$proname = $provalue;
    }

}
$obj = new Dome('peter','30');
echo $obj->name;
//给age赋值操作
$obj->age = 130;
echo '$obj->age';


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