The Singleton pattern possesses two general features:
The default class constructor cannot be called. Instead, it will be called through a designated class maintainer method that ensures only one instantiation is available at any given time.
A static class member that holds a reference to the existing class resource identifier.
Let's build a PHP class using the Singleton development pattern. Suppose that you're creating a Web-based action game. Of course, there can be one and only one hero, and therefore we need to ensure that only one exists at any given time. Sounds like a perfect reason to use the Singleton pattern! In Listing 1-1, I create a singleton class titled Hero(), and show you how even multiple instantiations yield the same object.
Listing 1-1. A PHP-based singleton pattern implementation
<?php
class Hero {
private static $exists = NULL;
private $name = "Superhero";
private function __construct() {
// No implementation.
}
static function introduce() {
if (self::$exists === NULL) {
self::$exists = new Hero();
}
return self::$exists;
}
function setName($name) {
$this->name = $name;
}
function getName() {
return $this->name;
}
} #end class Hero
$hero = Hero::introduce();
$hero->setName("Lance");
var_dump($hero);
echo "The hero's name is: ".$hero->getName()."<br />";
$hero2 = Hero::introduce();
var_dump($hero2);
echo "The hero's name is: ".$hero2->getName()."<br />";
$hero2->setName("Bruce");
echo "The hero's name is: ".$hero->getName()."<br />";
echo "The hero's name is: ".$hero2->getName()."<br />";
?>
Executing this example yields:
object(Hero)#1 (1) { } The hero's name is: Lance.
object(Hero)#1 (1) { } The hero's name is: Lance
The hero's name is: Bruce
The hero's name is: Bruce
As you can see by the above output, we're only dealing with one instance of the class throughout the entire example.
Add www.developer.com to your favorites Add www.developer.com to your browser search box IE 7 | Firefox 2.0 | Firefox 1.5.xReceive news via our XML/RSS feed