开发者

Static methods and Singleton in PHP

I have the next class:

class MyCl开发者_如何学Goass {
    private $_instance = null;
    private function __clone() {}
    private function __construct() {}
    public static function instance()
    {
        if (is_null(self::$_instance)) {
            self::$_instance = new self;
        }
        return self::$_instance;
    }

    public static function methodOne() {}
    public static function methodTwo() {}
    public static function methodThree() {}
    public static function methodFour() {}
}

And I have a lot of methods method...(). But this methods can be executable only if instance is not null. How can I throw an exception if instance is null?

I need to use only static methods. I can not use non-static. I want to use the next design:

MyClass::instance();
MyClass::methodOne(); // If no instance throws an Exception.


Do not make the methods static, only keep instance() static.

It will lead to:

$m = MyClass::instance();
$m->methodOne();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜