PHP Don't allow object to instantiate more than once

浪子不回头ぞ 提交于 2020-01-14 05:35:10

问题


I have an abstract class that is inherited by a number of other classes. I'd like to have it so that instead of re-instantiating (__construct()) the same class each time, to have it only initialize once, and utilize the properties of the previously inherited classes.

I'm using this in my construct:

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

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

This works - sort of, I'm able to get the properties and re-assign them, but within this, I also want to call some other classes, but only one time.

Any suggestions for a better way to go about doing this?


回答1:


Thats a Singleton construct:

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;
    }
}

I made the constructor and __clone() private final to hinder people from cloning and directly instanciating it. You can get the Singleton instance via MyClass::getInstance()

If you want an abstract base-singleton class have a look at this: https://github.com/WoltLab/WCF/blob/master/wcfsetup/install/files/lib/system/SingletonFactory.class.php




回答2:


You're referring to the Singleton pattern:

class Foo {
    private static $instance;

    private function __construct() {
    }

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

        return static::$instance;
    }
}


来源:https://stackoverflow.com/questions/8994541/php-dont-allow-object-to-instantiate-more-than-once

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!