Alex Pliutau
Alex Pliutau

Reputation: 21957

Static methods and Singleton in PHP

I have the next class:

class MyClass {
    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.

Upvotes: 0

Views: 815

Answers (1)

chelmertz
chelmertz

Reputation: 20601

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

It will lead to:

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

Upvotes: 3

Related Questions