RSS RSS feed
November 07, 2009
Hot Topics:

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

<?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.

1 2 3




Networking Solutions





Partners

  • Partner With Us














More for Developers

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs