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

PHP 物件生命週期:__construct 初始化與 __destruct 解構完整示範

     編輯:PHP 相關知識

__construct 在 new 時自動呼叫,用於初始化屬性、建立資源連線;__destruct 在物件被銷毀 (引用計數歸零、腳本結束) 前呼叫,用於釋放資源、寫入日誌、關閉連線。

基本語法與執行順序

<?php
class Database {
    private PDO $pdo;
    public function __construct(string $dsn, string $user, string $pass) {
        $this->pdo = new PDO($dsn, $user, $pass);
        echo "Connected\n";
    }
    public function query(string $sql) { return $this->pdo->query($sql); }
    public function __destruct() {
        $this->pdo = null; // 關閉連線
        echo "Disconnected\n";
    }
}

$db = new Database('sqlite::memory:', '', '');
$db->query('CREATE TABLE t (id INT)');
unset($db); // 立即觸發 __destruct
echo "Script end\n";
/*
輸出順序:
Connected
Disconnected
Script end
*/
?>

關鍵特性

  • 後進先出 (LIFO):多個物件銷毀順序與建立順序相反。
  • 腳本結束自動觸發:無需手動 unset,但資源釋放時機不可控。
  • 例外處理:__construct 拋出例外時,__destruct 不會被呼叫 (物件未建構完成)。
  • 不可接受參數:__destruct 不能有參數。
  • 循環引用:PHP 5.3+ GC 會處理,但 __destruct 執行順序不保證,避免在解構函式中依賴其他物件。

實務應用模式

1. 資源自動管理 (RAII 風格)

<?php
class FileLock {
    private $fp;
    public function __construct(string $file) {
        $this->fp = fopen($file, 'c+');
        flock($this->fp, LOCK_EX);
    }
    public function __destruct() {
        flock($this->fp, LOCK_UN);
        fclose($this->fp);
    }
}

// 使用
$lock = new FileLock('/tmp/app.lock');
// 關鍵區段...
unset($lock); // 自動釋放鎖
?>

2. 延遲寫入 / 批次提交

<?php
class BufferWriter {
    private array $buffer = [];
    private string $file;
    public function __construct(string $file) { $this->file = $file; }
    public function write(string $line) { $this->buffer[] = $line; }
    public function __destruct() {
        if ($this->buffer) {
            file_put_contents($this->file, implode("\n", $this->buffer), FILE_APPEND | LOCK_EX);
        }
    }
}

$log = new BufferWriter('/var/log/app.log');
$log->write('Event A');
$log->write('Event B');
// 腳本結束自動寫入
?>

⚠️ 避坑指南

  • 不要在 __destruct 中拋出例外 (會導致 Fatal Error)。
  • 不要依賴 __destruct 執行關鍵業務邏輯 (如資料庫寫入),改用明確的 save() 或 commit() 方法。
  • 長期運行腳本 (CLI Daemon) 需手動 unset 或 $obj = null 及時釋放資源。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved