Tags

, ,

Some application resources are exclusive in that there is one and only one of this type of resource. For example, the connection to a database through the database handle is exclusive. You want to share the database handle in an application because it’s an overhead to keep opening and closing connections, particularly during a single page fetch.

/*
 * Singleton
*/
Class DBconnection {
	private $conn = null;
	
	private function __construct() {

		$this->conn = mysql_connect('localhost', 'root', '');
		if (!$this->conn) {
			die('Could not connect: ' . mysql_error());
		}
	}
	
	public static function connect() {
		static $db = null;
		
		if ($db == null) {
			$db = new DBconnection();
		}  
		
		return $db;
	}
	
	public function connectionId() {
		return $this->conn;
	}
	

}

print( "ResourceId = ".DBconnection::connect()->connectionId()."<br />" );
print( "ResourceId = ".DBconnection::connect()->connectionId()."<br />" );
print( "ResourceId = ".DBconnection::connect()->connectionId()."<br />" );

Advertisements