PHP 5 引入了統一的建構子命名慣例(__construct())與全新的解構子機制(__destruct()),配合可視性關鍵字(public、protected、private),奠定了現代 PHP 物件導向程式設計的基礎。本文將系統性說明這三大核心概念的語法、行為與實務應用。
__construct()(PHP 4 風格的同名建構子仍相容,但不建議使用)new ClassName() 實例化時自動呼叫,不可手動呼叫func_get_args() 實現彈性參數class Person {
public $name;
public $sex;
public $age;
public function __construct($name, $sex, $age) {
$this->name = $name;
$this->sex = $sex;
$this->age = $age;
}
public function say() {
echo "我的名字叫:{$this->name} 性別:{$this->sex} 年齡:{$this->age}
";
}
}
$p1 = new Person('張三', '男', 20);
$p2 = new Person('李四', '女', 30);
$p1->say(); // 輸出:我的名字叫:張三 性別:男 年齡:20
$p2->say(); // 輸出:我的名字叫:李四 性別:女 年齡:30
class Database {
private $pdo;
public function __construct(
string $host = 'localhost',
string $dbname = 'test',
string $user = 'root',
string $pass = '',
int $port = 3306
) {
$dsn = "mysql:host={$host};port={$port};dbname={$dbname};charset=utf8mb4";
$this->pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
}
}
__destruct(),不接受任何參數unset())或超出作用域、腳本結束時自動呼叫exit()、致命錯誤)解構子仍會執行,但若在解構子中拋出例外會導致致命錯誤class FileHandler {
private $handle;
public function __construct(string $filename, string $mode = 'r') {
$this->handle = fopen($filename, $mode);
if (!$this->handle) {
throw new RuntimeException("無法開啟檔案:{$filename}");
}
}
public function readAll(): string {
return fread($this->handle, filesize($filename));
}
public function __destruct() {
if (is_resource($this->handle)) {
fclose($this->handle);
echo "檔案控制代碼已釋放
";
}
}
}
$handler = new FileHandler('data.txt');
echo $handler->readAll();
// 腳本結束時自動呼叫 __destruct() 關閉檔案
| 關鍵字 | 類別內部 | 子類別 | 外部程式碼 |
|---|---|---|---|
public | ✓ | ✓ | ✓ |
protected | ✓ | ✓ | ✗ |
private | ✓ | ✗ | ✗ |
class BankAccount {
private $balance = 0;
private $transactionLog = [];
public function __construct(float $initialBalance = 0) {
if ($initialBalance < 0) {
throw new InvalidArgumentException('初始餘額不可為負數');
}
$this->balance = $initialBalance;
}
// 唯讀存取器
public function getBalance(): float {
return $this->balance;
}
// 受控寫入器(存款)
public function deposit(float $amount): bool {
if ($amount <= 0) return false;
$this->balance += $amount;
$this->logTransaction('deposit', $amount);
return true;
}
// 受控寫入器(提款)
public function withdraw(float $amount): bool {
if ($amount <= 0 || $amount > $this->balance) return false;
$this->balance -= $amount;
$this->logTransaction('withdraw', $amount);
return true;
}
private function logTransaction(string $type, float $amount): void {
$this->transactionLog[] = [
'type' => $type,
'amount' => $amount,
'balance' => $this->balance,
'time' => date('Y-m-d H:i:s')
];
}
public function getTransactionLog(): array {
return $this->transactionLog; // 回傳副本更安全
}
}
$account = new BankAccount(1000);
$account->deposit(500);
$account->withdraw(200);
echo "目前餘額:{$account->getBalance()}"; // 1300
// $account->balance = -9999; // 錯誤:Cannot access private property
建構子是初始化私有屬性的主要管道,因為建構子預設為 public,外部可透過建構子參數安全地設定初始狀態:
class User {
private $id;
private $email;
private $passwordHash;
private $createdAt;
public function __construct(string $email, string $plainPassword) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException('Email 格式錯誤');
}
$this->email = $email;
$this->passwordHash = password_hash($plainPassword, PASSWORD_DEFAULT);
$this->createdAt = new DateTimeImmutable();
}
public function verifyPassword(string $plainPassword): bool {
return password_verify($plainPassword, $this->passwordHash);
}
// 唯讀屬性存取器
public function getEmail(): string { return $this->email; }
public function getCreatedAt(): DateTimeImmutable { return $this->createdAt; }
}
new 實例化(除非使用靜態工廠方法)isset() 或捕獲錯誤parent::__construct()建構子(__construct)負責物件誕生時的初始化,解構子(__destruct)負責物件銷毀前的清理,封裝性(private/protected/public)則定義了物件與外界的互動邊界。三者協同構成了 PHP 物件生命週期管理與資料保護的完整體系。掌握這些核心機制,是編寫健壯、可維護 PHP 程式碼的關鍵。