Skip to content

Instantly share code, notes, and snippets.

@andersonqi
Last active August 29, 2015 14:07
Show Gist options
  • Save andersonqi/80fba4d1fec116273a5c to your computer and use it in GitHub Desktop.
Save andersonqi/80fba4d1fec116273a5c to your computer and use it in GitHub Desktop.
Connect Mysql Singleton Pattern
<?php
/**
* Mysql database class
*/
class Database {
private $connection;
private $hostname = "hostname";
private $username = "username";
private $password = "password";
private $database = "database";
private static $instance; //The single instance
// The function construct is private to prevent the object can be created by new
private function __construct() {
$this->connection = new mysqli($this->hostname, $this->username,
$this->password, $this->database);
// Error handling
if(mysqli_connect_error()) {
trigger_error("Failed to conencto to MySQL: " . mysql_connect_error(),
E_USER_ERROR);
}
}
public static function getInstance() {
if(!self::$instance) { // If no instance then make one
self::$instance = new self();
}
return self::$instance;
}
// Magic method clone is empty to prevent duplication of connection
private function __clone() { }
// Get mysqli connection
public function getConnection() {
return $this->connection;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment