Clinton Montague

Developer, learner of things, functional programming enthusiast, hacker, and all round inquisitor.

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.

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:

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:

Happy Singleton-ing