Blogger Information
Blog 33
fans 0
comment 2
visits 41925
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP面向对象编程:属性访问方法_get()、_set()
hanyufeng的博客
Original
1170 people have browsed it

要严格遵守封装性原则,应避免直接从类的外部访问类的成员属性(设置为private),但如果都逐个编写访问函数,则又过于繁琐。

属性访问方法__get()、__set()用于解决这个问题,既保证了封装性,又节省了工作量。

这两个方法会被自动调用(在访问属性时),PHP 将这类方法称为魔术方法(Magic methods)。

PHP 的所有魔术方法都以 __(两个下划线)开头,所以在定义类方法时,除了魔术方法,建议不要以 __ 为前缀。

示例:

class Student
{
    private $name; //私有属性,外部不可访问
    private $grade; //私有属性,外部不可访问
    private $class; //私有属性,外部不可访问
 
    //__get()方法获取私有属性值
    public function __get($propertyName){
        return $this->$propertyName;
    }
 
    //__set()方法设置私有属性值
    public function __set($propertyName,$value){
        $this->$propertyName = $value;
    }
}
 
$stu = new Student();
$stu->name = 'zhangsan';
$stu->grade = '2015级';
echo $stu->name;
echo '<br>';
echo $stu->grade;

运行效果:

zhangsan
2015级

__get()、__set()方法只需要添加一次,可以用于private、protected属性的访问。

扩展:

如果需要,还可以在__get()、__set()方法中添加其它代码,进行一些处理,例如按照有无权限进行过滤。

如果访问的是不存在的属性,则会创建一个public 属性,例如:

class Student
{
    protected $name; //私有属性,外部不可访问
    private $grade = '2015级'; //私有属性,外部不可访问
 
    //__get()方法获取私有属性值
    public function __get($propertyName){
        return $this->$propertyName;
    }
 
    //__set()方法设置私有属性值
    public function __set($propertyName,$value){
        $this->$propertyName = $value;
    }
}
$stu = new Student();
$stu->class = '1班';  //访问类中不存在的属性 class
var_dump($stu);

运行结果:

object(Student)[1]  protected 'name' => null
  private 'grade' => string '2015级' (length=7)
  public 'class' => string '1班' (length=4)


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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!