php 单例模式

1,单例模式,属于创建设计模式,简单来说就是一个类只能有一个实例化对象,并提供一个当前类的全局唯一可访问入口;

2,例子

php 复制代码
<?php
 
class Singleton
{
    private static $instance = null;
 
    // 禁止被实例化
    private function __construct()
    {
 
    }
 
    // 禁止clone
    private function __clone()
    {
 
    }
        //  实例化自己并保存到$instance中,已实例化则直接调用
    public static function getInstance(): object
    {
        if (empty(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
 
    
}
 
// 两次调用返回同一个实例
$single1 = Singleton::getInstance();
$single2 = Singleton::getInstance();
 

可继承的单例模式:

php 复制代码
abstract class Singleton
{

    // 受保护的构造函数,确保不能通过 new 关键字直接实例化对象
    protected function __construct()
    {
        // 初始化操作
    }

    // 防止对象被复制
    protected function __clone()
    {
        throw new Exception("Singleton instance cannot be cloned.");
    }

    // 防止对象被序列化
    protected function __wakeup()
    {
        throw new Exception("Singleton instance cannot be serialized.");
    }

    // 获取实例的静态方法
    public static function getInstance()
    {
        if (!static::$instance) {
            static::$instance = new static();
        }
        return static::$instance;
    }
    // 其他业务方法
}

class SubSingleton extends Singleton
{
    protected static $instance=null;
    // 添加其他额外的功能或覆盖父类的方法
}

class Sub extends Singleton
{
    protected static $instance=null;
    // 添加其他额外的功能或覆盖父类的方法
}

//$singleton1和$singleton2 是同一个实例
$sub1 = Sub::getInstance();
$sub2 = Sub::getInstance();
var_dump($sub1);//object(Sub)#1 (0) { }
var_dump($sub2);//object(Sub)#1 (0) { }

//$subSingleton1 和subSingleton2是同一个实例
$subSingleton1 = SubSingleton::getInstance();
$subSingleton2 = SubSingleton::getInstance();
var_dump($subSingleton1);//object(SubSingleton)#2
var_dump($subSingleton2);//object(SubSingleton)#2
相关推荐
JaguarJack2 天前
FrankenPHP 原生支持 Windows 了
后端·php·服务端
BingoGo2 天前
FrankenPHP 原生支持 Windows 了
后端·php
JaguarJack3 天前
PHP 的异步编程 该怎么选择
后端·php·服务端
BingoGo3 天前
PHP 的异步编程 该怎么选择
后端·php
JaguarJack4 天前
为什么 PHP 闭包要加 static?
后端·php·服务端
ServBay5 天前
垃圾堆里编码?真的不要怪 PHP 不行
后端·php
用户962377954485 天前
CTF 伪协议
php
BingoGo7 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php
JaguarJack7 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php·服务端
BingoGo8 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php