Design Patterns: Singleton
The singleton design pattern is a way of enforcing only one instance of an object. This is achieved by making 3 fairly simple steps to a class. Firstly making the constructor private, creating a static member variable that will contain the instance and then creating a static method for accessing the instance.
So, In PHP it would be;
-
class Foo {
-
-
-
private function __construct(){
-
// Private, so can’t be accessed from outside
-
}
-
-
if($this->instance == null) {
-
$this->instance = new Foo();
-
}
-
return $this->instance;
-
}
-
-
public function bar(){
-
echo "I am one, I am a singleton!";
-
}
-
-
}
-
-
// Example usage
-
$foo = Foo::getInstance();
-
$foo->bar();
-
// or the chaining method
-
Foo::getInstance()->bar();
-
// Note this will not work
-
$myfoo = new Foo();
Why are singletons good? It’s almost like a global object right? What is good about a singleton as opposed to a concrete class? A concrete class has more flexibility as you can create multiple instances and then each instance can of course be different. However, what if you only ever want one instance of an object and ensure you don’t accidentally make another instance (or another developer doesn’t). You could use globals but they need to be managed somehow and people can still make mistakes and forget things.
The most common example is a database class, you might want to make sure that you only open one connection to the database. Creating multiple instances of database class could (depending how you programmed it) open multiple database connections and be inefficient.
The singleton can also be useful if an object that is used infrequently across a website. It can provide you easy access to it without having to worry about passing the object around. In the above code, you can access that object instance with this snippet of code “Foo::getInstance();”.

March 13th, 2009 at 5:47 pm
Thanks for this tip!
March 14th, 2009 at 7:06 am
Defining a private constructor is wrong.
You should either define __construct as public, or not at all.
I don’t mean to sound like I know it all, or rude, but your example has already confused at least one person into thinking they can define private constructors. Their confusion is what lead me here.
March 14th, 2009 at 11:56 am
Actually, you are completely incorrect.
Private constructors are perfectly valid and you’ve just shown that you don’t actually understand the concept behind a singleton. You may find it useful to re-read my post or go and read about a singleton in other websites as its often covered.
If you are still sure I am wrong, please back up your arguments with something. What you said summarises as: “You are wrong” and it isn’t the most persuasive comment I’ve ever read.
So yeah, private constructors are fine and can be used quite happily.