使应用中只存在一个对象的实例,并且使这个单实例负责所有对该对象的调用
final class Singleton{ private static ?Singleton $instance = null; public static function getInstance(): Singleton { if (static::$instance === ) { static::$instance = new (); } return ::$instance; } private function __construct(){ } function __clone(){ } function __wakeup(){ } }
类型前面的问号表示参数或返回值可为空(null),是PHP7的新特性
例如,?string $str 表示$str的值可以为null或字符串
此用法不只局限于静态类型,类和接口也可使用,例如,?MyInterface