Created
February 15, 2018 11:39
-
-
Save 0xWDG/e8bea5ca1b4429bd4da8fca61307ceeb to your computer and use it in GitHub Desktop.
PHP_Singleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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