單例模式確保類別全域只有一個實例,並提供全域存取點。適用於資料庫連線、設定管理、日誌記錄器等共享資源。
<?php
class Singleton {
private static ?self $instance = null;
private string $name = '';
private function __construct() {}
private function __clone() {}
public function __wakeup() {
throw new Exception("Cannot unserialize singleton");
}
public static function getInstance(): self {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function setName(string $name): void { $this->name = $name; }
public function getName(): string { return $this->name; }
}
// 使用
$s = Singleton::getInstance();
$s->setName('first');
echo '$s: ' . $s->getName() . "\n"; // first
unset($s); // 變數銷毀,實例仍在靜態屬性中
$m = Singleton::getInstance();
echo '$m: ' . $m->getName() . "\n"; // first (同一實例)
?>
private __construct:防止外部 newprivate __clone:防止 clone__wakeup:防止反序列化建立新實例static $instance:儲存唯一實例static getInstance():全域存取點final class Singleton {
private static ?self $instance = null;
public readonly string $createdAt;
private function __construct() {
$this->createdAt = (new DateTime())->format('c');
}
public static function getInstance(): self {
return self::$instance ??= new self();
}
}
理解單例優缺點,現代專案優先考慮 DI 容器管理共享服務。