Categories
PHP Programming

Design patterns: singletons

Singleton classes basically mean there is only one object class of a certain type running at all times. That could be used to store Global variables, for example.

The way to implement it on PHP:

class Preferences {
    private $props = array();
    private static $instance;

    private function __construct() { }  // By setting the class constructor to private, it can’t be instantiated from outside

    public static function getInstance() { // This static method will serve as instantiation, or to serve the only instance available
         if ( empty( self::$instance ) ) {
              self::$instance = new Preferences();
         }
         return self::$instance;
      }

      public function setProperty( $key, $val ) {
          $this->props[$key] = $val;
      }

      public function getProperty( $key ) {
          return $this->props[$key];
      }
}

Example of the driver class that is calling this:

$pref = Preferences::getInstance();
$pref->setProperty( “name”, “matt” );

unset( $pref ); // remove the reference

$pref2 = Preferences::getInstance();
print $pref2->getProperty( “name” ) .”n”; // demonstrate value is not lost

Leave a Reply

Your email address will not be published. Required fields are marked *