【发布时间】:2011-09-22 09:52:25
【问题描述】:
我有下一堂课:
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() {}
}
而且我有很多方法method...()。但是只有当instance 不为空时,此方法才能执行。如果instance 为空,如何抛出异常?
我只需要使用static 方法。我不能使用非静态的。我想使用下一个设计:
MyClass::instance();
MyClass::methodOne(); // If no instance throws an Exception.
【问题讨论】:
-
throw new Exception('message here'):) -
为什么要明确地这样做?如果您尝试使用
$instance,无论如何您都会遇到致命错误。此外,您似乎在这里非常滥用单例(这已经很糟糕了)。你到底想完成什么? -
我需要使用静态方法。
-
@stereofrog:哎呀,很抱歉偷了你的答案(我怪我写得慢)。
-
你需要使用静态方法,你还需要让它们表现得像实例方法?有点不对劲。
标签: php oop design-patterns exception singleton