【问题标题】:Static methods and Singleton in PHPPHP中的静态方法和单例
【发布时间】: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


【解决方案1】:

不要使方法静态,只保持instance()静态。

这会导致:

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

【讨论】:

  • 我知道。通过我想创建下一个设计: MyClass::instance(); MyClass:methodTwo();
  • +1 你不需要静态方法。有一个单身人士有点意思。您可以在任何地方静态访问它。
  • 此外,如果只使用静态方法,为什么还需要单例?静态方法是类函数,因此不需要类的实例。
猜你喜欢
  • 2012-09-25
  • 2011-03-26
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 1970-01-01
  • 2018-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多