David
David

Reputation: 509

PHP Don't allow object to instantiate more than once

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?

Upvotes: 0

Views: 3209

Answers (2)

FtDRbwLXw6
FtDRbwLXw6

Reputation: 28899

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

Upvotes: 1

TimWolla
TimWolla

Reputation: 32701

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

Upvotes: 9

Related Questions