Unhidden Content - Enjoy The View!
Pro PHP Patterns, Frameworks, Testing ลองๆดูนะคัฟน่าจะได้อะไรใหม่ๆ



Listing 3-1 shows an example of a singleton class designed to encapsulate a database
connection object.
Listing 3-1. Centralizing Database Connection Responsibility
class Database {
private $_db;
static $_instance;
private function __construct() {
$this->_db = pg_connect('dbname=example_db');
}
private __clone() {};
public static function getInstance() {
if( ! (self::$_instance instanceof self) ) {
self::$_instance = new self();
}
return self::$_instance;
}
public function query($sql) {
//Run a query using $this->_db
return pg_query($this->_db,$sql);
}
}
This example begins with the declaration of two variables: an instance variable $_db, that
will be populated when the object is constructed, and a static variable $_instance, which will
hold the only instance of the class.



Unhidden Content - Enjoy The View!
**Hidden Content: Thanks to see the content**