php单例实现
单例模式简介
单例模式是一种创建型设计模式,确保一个类只有一个实例,并提供全局访问点。适用于需要控制资源访问或限制实例数量的场景,如数据库连接、日志系统等。
基本实现步骤
私有化构造函数
防止外部通过new关键字创建实例:
private function __construct() {}
私有化克隆方法 防止通过克隆创建新实例:
private function __clone() {}
私有化反序列化方法 防止通过反序列化创建新实例(PHP 7.4+):
private function __wakeup() {}
静态私有属性保存实例
private static $instance = null;
静态公共方法获取实例
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
完整代码示例
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原生单例在CLI模式下多线程时可能需加锁:
public static function getInstance() {
if (self::$instance === null) {
$lock = fopen(__FILE__, 'r');
flock($lock, LOCK_EX);
if (self::$instance === null) {
self::$instance = new self();
}
flock($lock, LOCK_UN);
fclose($lock);
}
return self::$instance;
}
实际应用示例
数据库连接单例:

class DBConnection {
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;
}
}
注意事项
- 单例模式可能引入全局状态,测试时需谨慎
- 考虑依赖注入替代方案以提高可测试性
- 单例生命周期与请求周期相同,长时间运行的脚本需注意内存管理






