PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
How can I make a class that populates a variable with the first instance of itself? I want to be able to call the class so that I can retrieve the first instantiated instance..
I don't want it to be a singleton, but I want to be able to retrieve the first instance without using a registry or global variable. Hence I figured this would work. Works great using $this.
class test {
private static $instance = false;
function __construct() {
if (self::$instance === false) {
self::$instance = $this;
}
}
public static function getInstance(){
return self::$instance;
}
}
$activate = new test();
// and I try to get the instance with..
$test = test::getInstance();
I don't understand the reason for putting the singleton logic in the constructor. Eeven if you had that same logic in the factory method for it you'd essentially have the same thing.
~astions, have you looked at using a registry? That would give you far more flexibility and allow to store mutliple instances if you wanted to, whilst still be able to refer to an instance over and over like a singleton without needing to pass it from object to object at each step.
It's in the constructor to ensure that the first instance is captured.
As far as a registry is concerned, I've considered that, but with this method, which might just very well be a new pattern, I avoid using a registry, I can get an instance of the class from any other class without using globals, and I can still create a new instance if I need to.
public static function getInstance(){
if (self::$instance === null) self::$instance = new test();
return self::$instance;
}
Otherwise, how can you be sure you'll return a singleton? For your code to work you need to already have a live instance before the singleton will be returned