php singleton design patterns example

Singleton Design Patterns is very well know and commonly used design pattern.
In this blog we will learn more about this design pattern. what is singleton design pattern and how to use this pattern, where to use this design pattern. Lets look at the singleton design pattern example in php.

In Following example I am creating class for database that will allow us to create only one object of database class.
we have static varible instance and static method getInstance. In getInstance method we are checking do we have previous instance active if so then return previous object instance otherwise create new object. var dump will return you see the output comment snippet and you will understand.

php singleton design patterns example:

		class Database {
	 	public static $instance;
		 public static function getInstance(){
		    if(!isset(Database::$instance) ) {
		    	Database::$instance = new Database();
		    }
		   return Database::$instance;
		 }
		 private function __cunstruct() {
		   /* private and cant create multiple objects */
		 }
		 public function getQuery(){
		    return "Test Query Data";
		 }
	}
	$dbObj = Database::getInstance();
	$dbObj2 = Database::getInstance();
	var_dump($dbObj);
	var_dump($dbObj2);
/*
output:
object(Database)[1]
object(Database)[1]
*/
Share this nice post:

Leave a Reply

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