PHP5 Singleton Design Pattern

The singleton design pattern allows you to insure that only one instance of an object exist at one time.  It is useful tool to prevent multiple connections to a database.  The skelton looks like this:

class MyClass{
     static private $instance = false;
 
     #This prevents the user of the class from creating an
     #instance of the object
     private function __construct(){}
     #This prevents the user from making a copy of the
     #instance
     private function __clone(){}
 
     #This is how the user gets an a single instance
     #of the class
     public function getInstance(){
           #if the static instance attribute is false
           #then create the first and only instance of
           #the class
           if(!MyClass::$instance){
                MyClass::$instance = new MyClass();
           }
           return MyClass::$instance;
     }
 
     #Here you can put all of your members and attributes
     #that your class needs.

}

To get the instance of the the class you will need to invoke the getInstance method using the double-colon notation.

$myVar = MyClass::getInstance();

Leave a Reply