joschua011
joschua011

Reputation: 4207

Access property of 'singleton' class PHP

I am not sure whether the technique I use is appropriate or not. I have a class, singleton, with a subinstance like this:

final class Singleton {

    public $subinstance;
    private static $instance = NULL;

    private function __construct() {
        $this->subinstance = new subinstance(); 
    }

   public static function getInstance() {

       if (NULL === self::$instance) {
           self::$instance = new self;
       }

   return self::$instance;

   }

   private function __clone() {}
}

And now if I want to access the subinstance from outside the class in another class, I do:

$s = singleton::getInstance();
$s->subinstance->....

Is this the right way to do this? And what happens when I do $s=singleton::getInstance();, does the entire singleton class gets copied into $s or is this more like a pointer?

Upvotes: 0

Views: 993

Answers (2)

vegasje
vegasje

Reputation: 238

What you are doing is fine, although in your example code I'm assuming you meant to write:

$s = Singleton::getInstance(); // with the S capitalized

When you call the getInstance method, the class is looking to see if a version of itself has already been instantiated. If it has, it will return a reference to that instance instead of creating an entirely new instance. If the instance has not been created yet, it will create the instance and then return a reference to it.

I'm not sure why sixeightzero has stated that you shouldn't instantiate a class in the constructor of your instance. You shouldn't experience any issues when doing so.

Upvotes: 3

Mike Mackintosh
Mike Mackintosh

Reputation: 14245

If you do $a = singleton, $a will be a reference to the singleton class. Any changes in $a will reflect in access by singleton:: etc.. (pointer)

Why are you doing a subinstance in the constructor? This can cause issues, and should create a method to handle the subinstance outside the constructor inside a protected method. What does your subinstance look like?

Upvotes: 0

Related Questions