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
相关推荐
twcc_come19 小时前
安全策略配置实验报告
开发语言·php
weixin_BYSJ198720 小时前
springboot3家政平台小程序--附源码00904
java·javascript·spring boot·python·django·flask·php
上海安当技术1 天前
车间电脑指纹登录怎么做?从 FIDO2 公钥体系到统一身份认证的技术拆解
开发语言·电脑·php
大黄说说2 天前
接口频繁超时、报错?后端常见排查思路总结
开发语言·php
Sagittarius_A*2 天前
【RCELABS】Level 1~4 —— 基础篇
靶场·php·ctf·代码审计·rce
海天鹰2 天前
PHP换行
php
moonsims3 天前
星闪在跨域无人化系统作用
开发语言·php
灯澜忆梦3 天前
GO_网络编程---文件传输实战
网络·golang·php
happy_0x3f3 天前
前端应用的离线暂停更新策略
开发语言·前端·php
wWYy.3 天前
RPC详解
qt·rpc·php