標題是:PHP5中__get()、__set()方法,不錯,在PHP5以下(PHP4)是沒有這兩個方法的。
__get()方法:這個方法用來獲取私有成員屬性值的,有一個參數,參數傳入你要獲取的成員屬性的名稱,返回獲取的屬性值。如果成員屬性不封裝成私有的,對象本身就不會去自動調用這個方法。
__set()方法:這個方法用來為私有成員屬性設置值的,有兩個參數,第一個參數為你要為設置值的屬性名,第二個參數是要給屬性設置的值,沒有返回值。(key=>value)
/*
*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>";
}
}
?>
/*
*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 ?>
