php怎么实现单例模式
单例模式的概念
单例模式确保一个类只有一个实例,并提供一个全局访问点。在PHP中,常用于数据库连接、日志系统等需要全局唯一对象的场景。
实现单例模式的关键步骤
私有化构造函数
防止外部直接实例化对象,构造函数应声明为private:
private function __construct() {}
私有化克隆方法
防止通过克隆创建新实例,__clone方法也应声明为private:

private function __clone() {}
静态私有属性保存实例 使用静态私有属性存储类的唯一实例:
private static $instance;
静态公共方法获取实例 提供静态方法获取唯一实例,首次调用时创建实例,后续调用直接返回:

public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
完整代码示例
class Singleton {
private static $instance;
private function __construct() {}
private function __clone() {}
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
}
线程安全考虑(PHP多进程环境)
PHP默认是单线程运行,通常无需考虑线程安全。但在多进程环境下(如PHP-FPM),每个请求是独立进程,单例仅在当前请求生命周期内有效。
继承与单例模式
若需允许子类继承单例基类,可将构造函数改为protected,并在子类中实现自己的getInstance方法:
class ParentSingleton {
protected static $instance;
protected function __construct() {}
protected function __clone() {}
public static function getInstance() {
if (!isset(static::$instance)) {
static::$instance = new static();
}
return static::$instance;
}
}
class ChildSingleton extends ParentSingleton {
protected static $instance;
}
实际应用示例(数据库连接)
class Database {
private static $instance;
private $connection;
private function __construct() {
$this->connection = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
}
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
public function getConnection() {
return $this->connection;
}
}
// 使用方式
$db = Database::getInstance()->getConnection();






