PHP不允许对象多次实例化

时间:2012-01-24 21:36:21

标签: php class object

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

我在我的构造中使用它:

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

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

这很有用 - 我可以获取属性并重新分配它们,但在此之内,我还想调用其他一些类,但只有一次。

有什么建议可以更好地实现这一目标吗?

2 个答案:

答案 0 :(得分:8)

这是一个Singleton构造:

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() private final阻止人们克隆并直接实现它。您可以通过MyClass::getInstance()

获取Singleton实例

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

答案 1 :(得分:1)

你指的是Singleton模式:

class Foo {
    private static $instance;

    private function __construct() {
    }

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

        return static::$instance;
    }
}