【问题标题】:PHP Don't allow object to instantiate more than oncePHP 不允许对象多次实例化
【发布时间】:2012-01-24 21:36:21
【问题描述】:

我有一个抽象类,它被许多其他类继承。我想拥有它,而不是每次都重新实例化 (__construct()) 同一个类,让它只初始化一次,并利用以前继承的类的属性。

我在我的构造中使用这个:

function __construct() {
         self::$_instance =& $this;

         if (!empty(self::$_instance)) {
            foreach (self::$_instance as $key => $class) {
                     $this->$key = $class;
            }
         }
}

这行得通 - 有点,我能够获取属性并重新分配它们,但在此范围内,我还想调用其他一些类,但只有一次。

有什么更好的方法来做这件事的建议吗?

【问题讨论】:

标签: php class object


【解决方案1】:

这是一个单例结构:

class MyClass {
    private static $instance = null;
    private final function __construct() {
        //
    }
    private final function __clone() { }
    public final function __sleep() {
        throw new Exception('Serializing of Singletons is not allowed');
    }
    public static function getInstance() {
        if (self::$instance === null) self::$instance = new self();
        return self::$instance;
    }
}

我制作了构造函数和__clone()privatefinal来阻止人们克隆和直接实例化它。您可以通过MyClass::getInstance()获取Singleton实例

如果您想要一个抽象基单例类,请查看:https://github.com/WoltLab/WCF/blob/master/wcfsetup/install/files/lib/system/SingletonFactory.class.php

【讨论】:

  • +1 用于制作方法final,包括__clone(),这是我没有想到的。 :-)
  • 那么我是否让我的构造函数和我的构造函数一样?我在哪里使用 getInstance()?它仍然多次调用 __construct()
【解决方案2】:

您指的是单例模式:

class Foo {
    private static $instance;

    private function __construct() {
    }

    public static function getInstance() {
        if (!isset(static::$instance)) {
            static::$instance = new static();
        }

        return static::$instance;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    相关资源
    最近更新 更多