Hi. You've reached Nigel.in
This site is still in its very early stages, but what you have landed on, possibly inadvertently, is the website of a certain curious character a.k.a Nigel Fernandes
The aim of this page was to serve as a landing point for those of you who want to know a little more about me. The links on the right and left will take you deeper my world, or possibly on to different exciting things.
Its a big web out there and this is just one more street for you to saunter down. I hope you like it.
Close this.
About Me

- Name: Nigel Fernandes
- Location: Panjim, Goa, India
Crazy, dancing, programming, Goan.. I'm a computer geek and proud to be one. I program in Java, Ruby and .Net, PHP, Javascript. A lot of my recent work has been about CSS and UI design practices for large scale websites and Agile teams. I still while away hours dreaming up a web startup.
Implementing a Singleton Design pattern in PHP
Friday, February 29, 2008
Lets say you need your PHP web application to have one and only one instance of a class at a time.A simple way to achive this is to use the Singleton design pattern.
class Singleton {
private $myPrivateAttribute ;
private function __construct ( $aParameter ) {
$this->myPrivateAttribute = $aParameter ;
}
public static function make ( $aParameter ) {
static $instance = null ;
if ($instance == null) {
$instance = new Singleton ( $aParameter ) ;
}
return $instance ;
}
public function getAttributeValue () {
return $this->myPrivateAttribute ;
}
public function __clone () {
trigger_error ( 'Clone of a Singleton is invalid.', E_USER_ERROR ) ;
}
}
The reason this results in only a single object ever being created is that the Contructor is private. Hence you cannot create more objects of the Singleton class.To verify the Singleton's make() method is infact return the same object on multiple calls try the following code:
$object = Singleton::make("original");
echo $object->getAttributeValue(); // Will print "orginal"
$secondObject = Singleton::make("copy");
echo $object->getAttributeValue(); // Will print "orginal"
Labels: Design Patterns, PHP, Singleton