Codice PHP:
class Database
{
// A static property to hold the single instance of the class
private static $instance;
private static $db_host = "localhost";
private static $db_user = "root";
private static $db_pass = "";
private static $db_name = "my_dbname";
private $conn;
// The constructor is private so that outside code cannot instantiate
private function __construct() {
$conn = $this->connect($db_host, $db_user, $db_pass);
}
// All code that needs to get and instance of the class should call
// this function like so: $db = Database::getInstance();
public function getInstance()
{
// If there is no instance, create one
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// funzione per connettersi al database
public function connect( $db_host, $db_user, $db_pass ) {
if ( !mysql_connect( $db_host, $db_user, $db_pass ) ) {
throw new Exception( __CLASS__ . ': ' . mysql_error() );
} else {
$conn = mysql_connect( $db_host, $db_user, $db_pass );
mysql_select_db($db_name, $conn);
return $conn;
}
}
// Block the clone method
private function __clone() {}
}
// To use, call the static method to get the only instance
$db = Database::getInstance();
?>
va bene così?