[PHP] 单例模式-创建型设计模式

时间:2022-07-28
本文章向大家介绍[PHP] 单例模式-创建型设计模式,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

使应用中只存在一个对象的实例,并且使这个单实例负责所有对该对象的调用

final class Singleton{
    private static ?Singleton $instance = null;
    public static function getInstance(): Singleton
    {
        if (static::$instance === null) {
            static::$instance = new static();
        }
        return static::$instance;
    }
    private function __construct(){
    }
    private function __clone(){
    }
    private function __wakeup(){
    }
}

类型前面的问号表示参数或返回值可为空(null),是PHP7的新特性例如,?string str 表示str的值可以为null或字符串此用法不只局限于静态类型,类和接口也可使用,例如,?MyInterface