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
相关推荐
逝水如流年轻往返染尘14 分钟前
设计模式之单例模式
单例模式·设计模式
xxjj998a39 分钟前
PHP vs Java:核心区别与应用场景全解析
java·开发语言·php
isyangli_blog2 小时前
7. 使用Mininet 创建回环网络拓扑
服务器·网络·php
xxjj998a2 小时前
PHP vs Go vs Python:三大语言终极对比
python·golang·php
FYKJ_201013 小时前
springboot校园兼职平台--附源码02041
java·javascript·spring boot·python·eclipse·django·php
zhangfeng113318 小时前
PHP 语法检查命令 php -l “$file“ > /dev/null 2>&1;
开发语言·php
kybs199118 小时前
springboot视频推荐系统--附源码72953
java·spring boot·python·eclipse·asp.net·php·idea
计算机安禾18 小时前
【计算机网络】第6篇:虚拟局域网——基于标签的广播域划分及其安全边界
计算机网络·安全·php
zhangfeng113321 小时前
适合 5人以内小团队的Git 工作流 + Code Review + 自动化部署方案 FastAdmin +linunx服务器宝塔系统 外包项目 —
服务器·git·自动化·php·代码复审