PHP单例模式简单说明

admin2021-06-13设计模式4441
单例模式顾名思义,就是只有一个实例。作为对象的创建模式, 单例模式确保某一个类在程序的整个生命周期只有一个实例,而且自行实例化并向整个系统提供这个实例。
常用场景:日志
<?php 
class App {
    private $_instance = null;
    
    public static function instance(): static {
        // 判断$_instance变量是否为空
        return self::$_instance ?? self::$_instance = new static(); 
    }
    /**
    * deny clone
    **/
    private function __clone(){
        throw new \Exception("Can not clone this object")    
    }
}

// 调用方式
App::instance()->doSomeThings()

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。