What is A Singleton Class?
Singleton class is a class for which there exists only one object instance during the run time of the script (in php).
What is the use of singleton class?
It prevents the wastage of resources, if you have already established a connection to the database it retrieves that instance which already exists and reuses it. So there is no need to open a new connection.
How singleton class works?
First it searches for any object instance in the the run time of the script and returns it. If there is no object instance of this class it creates a new one…
Here is the database class which i normally use in my projects..
[php]
class Database{
// Store the single instance of Database
private static $instance;
private static $con;
private function __construct() {
//setup database.
//echo “constructor called”;
// use your server name , sql username and password db name here
$this->con=mysql_connect (“host”, “user”, “password”);
mysql_select_db (“database”,$this->con);
}
public static function getInstance()
{
if (!self::$instance)
{
self::$instance = new Database();
}
return self::$instance;
}
public static function closeInstance()
{
if (!(!self::$instance))
{
$inst = self::$instance;
mysql_close($inst->con);
}
}
// Function to run query
public function query($sql)
{
//echo “query run”;
return mysql_query($sql,$this->con);
}
}
[/php]
Usage:
Call a class using
[php]$db = Database::getInstance();[/php]
Query database
[php]$result = $db->query(‘sql statement here’);[/php]
Close Db Connection
[php]Database::closeInstance();[/php]
Thats all for now about the database class.. you no need to know how it works to use it but you need to study if you want to develop this.