1.__construct() 當實例化一個對象的時候,這個對象的這個方法首先被調用。java代碼 class Test { function __construct() { echo "before"; } } $t = new Test(); class Test { function __construct() { echo "before"; } } $t = new Test(); 輸出是: start 我們知道php5對象模型 和類名相同的函數(shù)是類的構造函數(shù),那么如果我們同時定義構造函數(shù)和__construct()方法的話,php5會默認調用構造函數(shù)而不會調用__construct()函數(shù),所以__construct()作為類的默認的構造函數(shù)2.__destruct() 當刪除一個對象或對象操作終止的時候,調用該方法。 Java代碼 class Test { function __destruct() { echo "end"; } } $t = new Test();將會輸出end class Test { function __destruct() { echo "end"; } } $t = new Test();將會輸出end 我們就可以在對象操作結束的時候進行釋放資源之類的操作 3.__get() 當試圖讀取一個并不存在的屬性的時候被調用。 如果試圖讀取一個對象并不存在的屬性的時候,PHP就會給出錯誤信息。如果在類里添加__get方法,并且我們可以用這個函數(shù)實現(xiàn)類似java中反射的各種操作。 Java代碼 class Test { public function __get($key) { echo $key . " 不存在"; } } $t = new Test(); echo $t->name; 就會輸出:name 不存在class Test { public function __get($key) { echo $key . " 不存在"; } } $t = new Test(); echo $t->name; 就會輸出:name 不存在4.__set() 當試圖向一個并不存在的屬性寫入值的時候被調用。 Java代碼 class Test { public function __set($key,$value) { echo '對'.$key . "附值".$value; } } $t = new Test(); $t->name = "aninggo"; 就會輸出:對 name 附值 aninggoclass Test { public function __set($key,$value) { echo '對'.$key . "附值".$value; } } $t = new Test(); $t->name = "aninggo"; 就會輸出:對 name 附值 aninggo5.__call() 當試圖調用一個對象并不存在的方法時,調用該方法。 Java代碼 class Test { public function __call($Key, $Args) { echo "您要調用的 {$Key} 方法不存在。你傳入的參數(shù)是:" . PRint_r($Args, true); } } $t = new Test(); $t->getName(aning,go);class Test { public function __call($Key, $Args) { echo "您要調用的 {$Key} 方法不存在。你傳入的參數(shù)是:" . print_r($Args, true); } } $t = new Test(); $t->getName(aning,go);程序將會輸出: Java代碼 您要調用的 getName 方法不存在。參數(shù)是:Array ( [0] => aning [1] => go ) 您要調用的 getName 方法不存在。參數(shù)是:Array ( [0] => aning [1] => go ) 6.__toString() 當打印一個對象的時候被調用 這個方法類似于java的toString方法,當我們直接打印對象的時候回調用這個函數(shù) class Test { public function __toString() { return "打印 Test"; } } $t = new Test(); echo $t;運行echo $t;的時候,就會調用$t->__toString();從而輸出 打印 Test 7.__clone() 當對象被克隆時,被調用 class Test { public function __clone() { echo "我被復制了!"; } }$t = new Test(); $t1 = clone $t;程序輸出:我被克隆了!