单例模式的实现PHP
单例模式的基本概念
单例模式是一种创建型设计模式,确保一个类只有一个实例,并提供全局访问点。适用于需要控制资源访问或共享状态的场景,如数据库连接、日志记录器等。
PHP 单例模式的实现步骤
私有化构造函数
防止外部通过 new 创建实例。将构造函数声明为 private 或 protected。
private function __construct() {}
静态私有属性保存实例
使用静态私有属性存储类的唯一实例。

private static $instance = null;
静态公有方法获取实例
提供静态方法检查是否已存在实例,若不存在则创建并返回。
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
防止克隆和反序列化

通过魔术方法禁止克隆和反序列化操作,确保唯一性。
private function __clone() {}
private function __wakeup() {}
完整代码示例
class Singleton {
private static $instance = null;
private function __construct() {}
private function __clone() {}
private function __wakeup() {}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
}
线程安全考虑
PHP 本身是单线程的(每个请求独立处理),通常无需考虑多线程问题。若在特殊环境(如 Swoole 协程)中,可加锁确保安全:
public static function getInstance() {
if (self::$instance === null) {
$lock = new \Swoole\Lock();
$lock->lock();
if (self::$instance === null) {
self::$instance = new self();
}
$lock->unlock();
}
return self::$instance;
}
使用场景示例
数据库连接管理:
class Database {
private static $instance = null;
private $connection;
private function __construct() {
$this->connection = new PDO("mysql:host=localhost;dbname=test", "user", "pass");
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function getConnection() {
return $this->connection;
}
}
// 使用方式
$db = Database::getInstance();
$conn = $db->getConnection();
注意事项
- 单例模式可能隐藏类之间的依赖关系,降低可测试性。
- 过度使用可能导致全局状态污染,需谨慎评估使用场景。





