Skip to content

Instantly share code, notes, and snippets.

@0xWDG
Created February 15, 2018 11:39
Show Gist options
  • Select an option

  • Save 0xWDG/e8bea5ca1b4429bd4da8fca61307ceeb to your computer and use it in GitHub Desktop.

Select an option

Save 0xWDG/e8bea5ca1b4429bd4da8fca61307ceeb to your computer and use it in GitHub Desktop.
PHP_Singleton
<?php
// Singleton to connect db.
class ConnectDb {
  // Hold the class instance.
  private static $instance = null;
  private $conn;
  
  private $host = 'localhost';
  private $user = 'db user-name';
  private $pass = 'db password';
  private $name = 'db name';
  
  // The db connection is established in the private constructor.
  private function __construct()
  {
    $this->conn = new PDO("mysql:host={$this->host};
    dbname={$this->name}", $this->user,$this->pass,
    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
  }
  
  public static function getInstance()
  {
    if(!self::$instance)
    {
      self::$instance = new ConnectDb();
    }
  
    return self::$instance;
  }
  
  public function getConnection()
  {
    return $this->conn;
  }
}
$instance = ConnectDb::getInstance();
$conn = $instance->getConnection();
var_dump($conn);
$instance = ConnectDb::getInstance();
$conn = $instance->getConnection();
var_dump($conn);
$instance = ConnectDb::getInstance();
$conn = $instance->getConnection();
var_dump($conn);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment