Singletons in PHP
November 16, 2008
Please note!! I have shamelessly stolen this article from my old and (even if I do say so myself) rather boring blog. So please ignore the terrible writing style! I’ll rewrite this article in the future, but until then, I present you with version 1.0
A project I’m currently working on has made use of the Singleton design pattern quite extensively. It’s something that I found a little frustrating to get working initially due to returning references of objects from functions. I knew about the &= assignment operator, but it took a lot of messing around before I finally turned to the php documentation to find out that an & needed to go before the function name (which returns the reference) too.
Below is a simple example of a singleton in action.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Class Singleton { private function __construct () { // initialise variables etc } public static function &getInstance () { static $instance; if (!isset ($instance)) { $instance = new Singleton (); } return $instance; } } |
Because the contructor is declared private, it’s not possible to create an instance from outside the class by using new Singleton (), doing so will create a fatal error. (You can write new Singleton () inside the getInstance() method because it is located inside of the class). Using this code is extremely simple:
1 |
var $foo =& Singleton::getInstance (); |
I hope that this will help a few people out so that they don’t suffer the same frustrations as myself.
I have uploaded a copy of a config file which I have written which makes use of this singleton code. Use as follows: I will upload a copy of a class which uses this design pattern. Usage is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$config =& Config::getConfig $config->set ('db', 'username', 'root'); $config->set ('db', 'password', 'password'); $config->set ('db', 'host', 'localhost'); $config->set ('db', 'database', 'db'); // blah blah $db_username = $config->get ('db', 'username'); // ... // if a 'index/subindex' pair has not been set, // it will return false $test = $config->get ('not', 'set'); // $test is false |
Happy Singleton-ing