Thursday, 9 February 2012

Single Design Pattern Example in PHP

<?PHP
/*
The Singleton ensures that there can be only one instance of a Class and provides a global access point to that instance. Singleton is a "Gang of Four" Creational Pattern.

The Singleton pattern is often implemented in Database Classes, Loggers, Front Controllers or Request and Response objects.

*/


    class Singleton
    {
        static private $instance;
        protected function __construct() {}
        final private function __clone() {}
       
        static function getInstance()
        {
            if(!self::$instance)
                self::$instance= new Singleton();
                return self::$instance;
        }
    }
   
    $a = Singleton::getInstance();
    $a->id=1;
    $b = Singleton::getInstance();
    print $b->id."\n";

?>

No comments:

Post a Comment