October 23, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Implementing Patterns within PHP

  • April 26, 2004
  • By W. Jason Gilmore
  • Send Email »
  • More Articles »

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

<?phpclass 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: LanceThe hero's name is: BruceThe 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.





Page 2 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel