首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 5 魔術方法深度解析:__construct、__destruct、__get、__set、__call、__toString、__clone 實戰用法

     編輯:PHP 相關知識

1. __construct() 構造器

class Test {
    function __construct() { echo "before"; }
}
$t = new Test(); // 輸出:before

若同時定義同名方法 function Test(),PHP 5 優先調用 __construct()。

2. __destruct() 解構器

class Test {
    function __destruct() { echo "end"; }
}
$t = new Test(); // 腳本結束或 unset($t) 時輸出:end

適用於釋放資源、關閉連接、寫入日誌。

3. __get($key) 讀取不可見屬性

class Test {
    public function __get($key) { echo "$key 不存在"; }
}
$t = new Test();
echo $t->name; // 輸出:name 不存在

4. __set($key, $value) 寫入不可見屬性

class Test {
    public function __set($key, $value) { echo "對 $key 附值 $value"; }
}
$t = new Test();
$t->name = "aninggo"; // 輸出:對 name 附值 aninggo

5. __call($method, $args) 調用不可見方法

class Test {
    public function __call($method, $args) {
        echo "您要調用的 {$method} 方法不存在。參數:" . print_r($args, true);
    }
}
$t = new Test();
$t->getName('aning', 'go');
/* 輸出:
您要調用的 getName 方法不存在。參數:
Array ( [0] => aning [1] => go )
*/

6. __toString() 對象轉字符串

class Test {
    public function __toString() { return "打印 Test"; }
}
$t = new Test();
echo $t; // 輸出:打印 Test

7. __clone() 克隆攔截

class Test {
    public function __clone() { echo "我被復制了!"; }
}
$t = new Test();
$t1 = clone $t; // 輸出:我被復制了!

可在克隆時深拷貝資源、重置標識符等。

最佳實踐

  • 統一使用 __construct/__destruct 替代舊式同名構造/解構方法。
  • __get/__set 配合 private 屬性實現屬性訪問控制、懶加載、數據驗證。
  • __call 用於動態代理、方法別名、AOP 攔截。
  • __toString 讓對象直接參與字符串拼接、日誌輸出。
  • __clone 確保克隆對象狀態獨立(如複製資源句柄、生成新 ID)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved