PHP单列实现,方便其它类继承使用

206次阅读
没有评论

static::class 在继承中自动识别调用类的类命,若是使用 CLASS 则在继承调用之后,仍是表示当前类(此示例中 Base 类)

new static() 与 new self() 使用注意同上。

// 单例
class Base
{
    // 存储当前对象
    protected static $instance  = [];

    private function __construct()
    { }

    private function __clone()
    { }

    public static function getInstance()
    {if(empty(static::$instance[static::class])){static::$instance[static::class] = new static();}
        return static::$instance[static::class];
    }
}
正文完
有偿技术支持加微信
post-qrcode
 
评论(没有评论)
验证码