PHP5中__get()、__set()方法

__get()方法:这个方法用来获取私有成员属性值的,有一个参数,参数传入你要获取的成员属性的名称,返回获取的属性值。如果成员属性不封装成私有的,对象本身就不会去自动调用这个方法。

__set()方法:这个方法用来为私有成员属性设置值的,有两个参数,第一个参数为你要为设置值的属性名,第二个参数是要给属性设置的值,没有返回值。(key=>value) 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
*person.class.php
*/
<?php
 
class Person{
 
    private $name;
    public $age;
    public $sex;
    public $addrs;
    public $time;
 
    function __construct($name,$age,$sex,$addrs){
        //parent::__construct();
        $this->name = $name;
        $this->age = $age;
        $this->sex = $sex;
        $this->addrs = $addrs;
    }
 
    private function __get($pri_name){
        if(isset($this->$pri_name)){
            echo "pri_name:".$this->$pri_name."<br>";
            return $this->$pri_name;
        }else{
            echo "不存在".$pri_name;
            return null;
        }
    }
 
    private function __set($pri_name,$value){
        echo $pri_name."的值为:".$value."<br>";
        $this->$pri_name $value;
    }
 
    function user($time){
        $this->time = $time;
        echo "我叫:".$this->name.",今年:".$this->age."岁,性别:".$this->sex.",地址是:".$this->addrs.",--".$this->time."<br>";
    }
 
    function __destruct(){
        echo "再见:".$this->name."<br>";
    }
 
}
 
?>

1
2
3
4
5
6
7
8
9
10
11
12
13
/*
*person.php
*/
<?php
    require "person.class.php";
 
    $Person new Person("xy404","22","男","湖北");
    $Person->user(404);
 
    $Person->name = "aib";  //在person.class.php中的person类中name这个属性private的。所以它在赋值的时候自动调用了__set()这个方法.如果没有__set()方法就会报错。
 
    echo $Person->name."<br>";
?>

输出的内容:

 

  •  在直接获取私有属性值的时候,自动调用了这个__get()方法。
  •  在直接设置私有属性值的时候,自动调用了这个__set()方法为私有属性赋值 

 

 

 一般在调用类的属性和方法的时候会使用:$this->name 或 $this->name()来完成。下面通过一个简单的例子来说明一下$this->$name的这种用法。

复制代码
 1 <?php
 2 class Test{
 3   public $name = "abc";
 4   public $abc = "test";
 5 
 6   public function Test(){
 7        $name1 = "name";
 8        echo $this->name;   // 输出 abc
 9        echo $this->$name1;  // 输出 abc,因为 $name1 的值是name,相当与这里替换成 echo $this->name;
10        $name2 = $this->$name1;  // $name2 的值是 abc
11        echo $this->$name2;  // 输出 test,同上,相当与是 echo $this->abc;
12   }
13 }
14 ?>
复制代码
posted @ 2017-01-09 20:29  天涯海角路  阅读(121)  评论(0)    收藏  举报