View Full Version : PHP singletone pattern in php files where AJAX's requests are sent

11-12-2011, 07:40 AM
I have an AJAX code which sends requests to multiple .php files in the server. All the files (that I send request) are using the same Db class and I think using sigleton pattern will help me out. But now I doubt that everytime I send request it creates a whole new objectn (instead of grabing the object hold by $instance static variable) . Is it correct ? And if so how can I make an instance only once . By the way on the top of all php files that I am sending request I type



And below is my Db class

require_once("includes/config.php"); // Configuration

class Db{
public $connection;
public $selected_db;
private static $instance;

public static function getSingletone(){
if(!self::$instance instanceof self){
self::$instance=new self();
return self::$instance;

public function __construct(){

$this->connection=mysql_connect(DB_HOST,DB_USER,DB_PASS); // 1 . Creating a connection
die("Couldnt create a database connection ". mysql_error());
$this->selected_db=mysql_select_db(DB_NAME,$this->connection); // 2. Selects a database
die("Could not select the database: ".mysql_error());
}// End "if" for selecting a database


public function insert($user,$time,$message){
$query="INSERT INTO chat(user,time,message) VALUES('{$user}','{$time}','{$message}')";
die("Could Not Insert ".mysql_error());

}// End "insert()" method

public function execute($query){

die("Database query failed".mysql_error());
return $result;
} // End "execute()" method

public function row_number($query){
return $result;

public function delete_rows($table){
$query="DELETE FROM '{$table}' WHERE id=7";
die("Could NOT delete".mysql_error());

} // End "delete_rows_by_ids()" method

public function __destruct(){ // __destruct()

} // Destroys created object

} // End the "db" class

11-13-2011, 03:31 AM
PHP doesn't keep objects in memory once the request is complete. You can use a singleton to reuse the object during the request, but once the script is complete it will be destroyed. PHP doesn't keep scripts running as a service like JAVA or CF would do.