單例模式確保某個類別在整個應用程式生命週期中只存在一個實例,並提供全域存取點。常用於資料庫連線、設定管理、日誌記錄等需要共享資源的場景。
<?php
/**
* 單例模式基礎實作
*/
class Single {
private $name;
private static $single = null;
// 私有建構子,防止外部 new Single()
private function __construct() {
}
// 防止複製
private function __clone() {
}
// 防止反序列化建立新實例
public function __wakeup() {
throw new Exception("Cannot unserialize a singleton.");
}
// 靜態工廠方法,取得唯一實例
public static function init() {
if (self::$single === null) {
self::$single = new Single();
}
return self::$single;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
}
// 使用示範
$s = Single::init();
$s->setName('hhhh');
echo '$s: ' . $s->getName() . "\n";
unset($s); // 釋放變數,但實例仍存在於 static 變數中
$m = Single::init();
echo '$m: ' . $m->getName() . "\n"; // 輸出 'hhhh',證明是同一實例
?>
private __construct():阻止 new Single()private __clone():阻止 clone $single__wakeup() 拋出例外:阻止 unserialize() 重建實例private static $single 儲存於類別層級,不屬於任何物件實例,生命週期贯穿整個請求。
只有首次呼叫 init() 時才建立實例,節省資源。
PHP 是單執行緒模型(除非使用 pthreads 擴展),一般 Web 應用不需雙重檢查鎖定。但若在支援多執行緒的環境下:
public static function init() {
if (self::$single === null) {
// PHP 一般環境不需此鎖,僅作示範
$lock = fopen(__FILE__, 'r');
flock($lock, LOCK_EX);
if (self::$single === null) {
self::$single = new Single();
}
flock($lock, LOCK_UN);
fclose($lock);
}
return self::$single;
}
class Database {
private static $instance = null;
private $pdo;
private function __construct() {
$this->pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function getConnection() {
return $this->pdo;
}
}
// 使用
$db = Database::getInstance()->getConnection();
$stmt = $db->query('SELECT * FROM users');
class Config {
private static $instance = null;
private $settings = [];
private function __construct() {
$this->settings = require __DIR__ . '/config.php';
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function get($key, $default = null) {
return $this->settings[$key] ?? $default;
}
}
// 使用
$appEnv = Config::getInstance()->get('app.env', 'production');
// 使用容器管理單例生命週期
$container = new Container();
$container->singleton(Database::class, function () {
return new Database('mysql:host=localhost;dbname=test', 'user', 'pass');
});
// 需要時由容器注入
class UserService {
public function __construct(private Database $db) {}
}
$userService = $container->get(UserService::class);
單例模式在 PHP 中實作簡單,透過私有建構子、靜態實例變數與工廠方法即可達成。雖然在資料庫連線、設定管理等場景實用,但現代開發推薦使用依賴注入容器管理共享實例,提升可測試性與維護性。理解單例模式原理有助於識別既有程式碼架構,並在適當場合權衡利弊。