PHP单例模式简单说明
单例模式顾名思义,就是只有一个实例。作为对象的创建模式, 单例模式确保某一个类在程序的整个生命周期只有一个实例,而且自行实例化并向整个系统提供这个实例。
常用场景:日志
<?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()