Blogger Information
Blog 61
fans 0
comment 0
visits 62895
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
魔术方法函数“__get()”和“__set()”来获取和赋值其属性,
Pengsir
Original
608 people have browsed it
<?php
class Car
{
    private $name='BMW';
    protected $price=2000000;
//__get():当用户访问一个不存在或无权限访问的属性的时候,自动调用
    public function __get($proName)
    {
        if($this->name=='BMW'){
            return $this->$proName;
        }else{
            return '<h3 style="color: red">无权访问</h3>';
        }
    }
//__set():当用户对一个不存在或者无权访问的属性进行赋值的时候自动调用
    public function __set($proName, $proValue)
    {
        if($proName=='price'){
            if($proValue>120000 &&$proValue<1000000){
                $this->price=$proValue;
            }else{
                echo '<h3 style="color: red">'.$proValue.'数据不正确</h3>';
            }
        }
        $this->$proName=$proValue;
    }
}
$obj1 =new Car();
echo $obj1->name;
echo '价格是:'. $obj1->price;
echo '<hr>';
$obj2 =new Car();
echo $obj2->name='尼桑';
echo '价格是:'. $obj2->price=120000;
echo '<hr>';

图:

魔术方法__ge()t和__set().png

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