Friday, May 28, 2010

What is Singleton Class

A singleton class allows only one instance of an object to be used across the web application.
Where it can be used:
  •  During Database Connection where we want to share only one database connection throughout the web application. So in this case make your database related operation through Singleton Design Pattern.
  • To avoid error like too many connection open.





class YourSingleTonClass
{
 private static $instance;
 
 private function __construct()
 {
 } 
 public function getInstance() {
  if($instance === null) {
   $instance = new YourSingleTonClass();
  }
  return $instance;
 }
}
Description of Logic:


  • Declare the constructor "private" so this can not be called outside of class.As constructor can not be called out side of class so this class cannot be instantiated.
  • Now declared an static variable $instance that will hold the object. With the static data type $instance will hold the object till the class is alive.
  • Now i have made one method called getInstance(), it will check whether $instance already has some object, if it already has some object then it will return that object instance otherwise will assign an new object to this variable.
  • so only one instance at any time, now implement this class for database connection to avoid error like too many connection open.
?>

No comments:

Post a Comment