php单实现

PHP 单例模式实现
单例模式是一种设计模式,确保一个类只有一个实例,并提供全局访问点。在 PHP 中,可以通过以下方式实现单例模式:
class Singleton {
private static $instance = null;
private function __construct() {
// 私有构造函数,防止外部实例化
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
private function __clone() {
// 私有克隆方法,防止克隆实例
}
private function __wakeup() {
// 私有反序列化方法,防止反序列化创建新实例
}
}
使用单例模式
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();
var_dump($instance1 === $instance2); // 输出 true,说明是同一个实例
关键点说明
- 私有构造函数:防止外部直接实例化对象。
- 静态变量
$instance:保存类的唯一实例。 - 静态方法
getInstance():提供全局访问点,确保只有一个实例被创建。 - 私有
__clone()和__wakeup()方法:防止通过克隆或反序列化创建新实例。
实际应用场景
单例模式适用于需要全局唯一实例的场景,例如数据库连接、日志记录器、配置管理等。通过单例模式可以避免重复创建对象,节省资源。
class Database {
private static $instance = null;
private $connection;
private function __construct() {
$this->connection = new PDO("mysql:host=localhost;dbname=test", "user", "password");
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
public function getConnection() {
return $this->connection;
}
private function __clone() {}
private function __wakeup() {}
}
$db = Database::getInstance();
$connection = $db->getConnection();
通过以上方式,可以确保在整个应用中只有一个数据库连接实例,避免多次连接数据库的开销。







