建構子是物件導向程式設計中,物件實例化時自動呼叫的特殊方法。主要用途:初始化物件屬性、建立資源連線、註冊事件監聽等。
| 版本 | 語法 | 說明 |
|---|---|---|
| PHP 4 | function ClassName() | 方法名與類別名相同 |
| PHP 5+ | function __construct() | **標準魔術方法**,與類別名解耦,重命名類別無需改建構子 |
| PHP 8.0+ | public function __construct(public string $name) {} | **建構子屬性提升**,自動宣告並賦值屬性 |
相容性:若類別無 __construct,PHP 會嘗試尋找同名方法(PHP 4 風格),但已不推薦使用。
class Person {
// PHP 8.0+ 建構子屬性提升寫法(最簡潔)
public function __construct(
public string $name,
public string $gender,
public int $age
) {}
// PHP 7.x 兼容寫法
// private string $name;
// private string $gender;
// private int $age;
// public function __construct(string $name, string $gender, int $age) {
// $this->name = $name;
// $this->gender = $gender;
// $this->age = $age;
// }
public function introduce(): string {
return "我是 {$this->name},{$this->gender},今年 {$this->age} 歲。";
}
}
// 實例化
$p1 = new Person('小明', '男', 25);
$p2 = new Person('小紅', '女', 22);
echo $p1->introduce(); // 我是 小明,男,今年 25 歲。
echo $p2->introduce(); // 我是 小紅,女,今年 22 歲。
new ClassName() 瞬間呼叫,無法手動呼叫($obj->__construct() 會報錯)。__construct。需多種建構方式請用 靜態工廠方法。__construct,**必須主動呼叫 parent::__construct()** 才會執行父類別初始化。: void 或不寫),否則致命錯誤。class User {
private function __construct(
public int $id,
public string $email,
public string $name
) {}
// 從資料庫資料建構
public static function fromDatabase(array $row): self {
return new self($row['id'], $row['email'], $row['name']);
}
// 從 API 回應建構
public static function fromApiResponse(array $data): self {
return new self($data['user_id'], $data['email'], $data['display_name']);
}
// 建立新用戶(ID 由資料庫自增)
public static function create(string $email, string $name): self {
return new self(0, $email, $name); // ID=0 表示新建
}
}
// 使用
$user1 = User::fromDatabase($dbRow);
$user2 = User::create('test@example.com', '新用戶');
__destruct **不會**被呼叫,需自行在 catch 區塊釋放資源。__construct 是物件生命週期的起點。善用 PHP 8 建構子屬性提升 減少樣板碼,配合 靜態工廠方法 實現多樣化建構邏輯,並堅持「建構子只做初始化、不做業務」原則,能寫出更乾淨、可測試、可維護的現代 PHP 程式碼。