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

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

相关文章:

  • 2018-06-14
  • 2021-12-09
  • 2021-07-28
  • 2021-11-12
  • 2021-06-17
  • 2022-01-13
猜你喜欢
  • 2021-06-19
  • 2021-08-21
  • 2021-12-04
  • 2021-10-19
  • 2021-10-18
  • 2022-01-30
  • 2022-12-23
相关资源
相似解决方案