Blogger Information
Blog 61
fans 0
comment 0
visits 54323
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
属性的重载操作
笑颜常开的博客
Original
618 people have browsed it

<?php
// 重载:
class Demo3
{
   private $name;
   private $salary;
   protected $secret = '其实猪哥与朱老师不是同一个人';
   // 构造方法
   public function __construct($name, $salary)
   {
       $this->name = $name;
       $this->salary = $salary;
   }
//    public function getName(){
//        return $this->name;
//    }
//    public function getSalary(){
//        return $this->salary;
//    }
//魔术方法:__get($name)当获取未定义可不见属性时触发
   public function __get($name){
//        $name:要访问的属性名称
       if ($name==='secret'){
           return ($this->name==='admin')?$this->$name:'无权查看';
       }
       return $this->$name;
   }
// 魔术方法:__set($name, $value)当设置未定义可不见属性赋值时触发
   public function __set($name, $value)
   {
// 直接返回, 极少这样做
// $this->$name = $value;
// 添加过滤机制
       if ($name === 'salary') {
           return $this->name === 'admin' ? $this->$name = $value : '无权更新';
       }
       return $this->$name = $value;
   }
}
$obj = new Demo3('admin', 6666);
echo $obj->name, '<br>';
echo $obj->secret, '<br>';

$obj->salary=10000;
echo '工资是:'.$obj->salary.'<br>';

//if(isset($obj->name)){
//    echo "你好";
//}
//else{
//    echo "失败";
//}

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