Last active
August 8, 2022 09:41
-
-
Save khamer/64cd02f06b52992ec59a to your computer and use it in GitHub Desktop.
Example of a Singleton Class
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 | |
| class ExampleDatabase { | |
| static private $instance = null; | |
| static public function getInstance() | |
| { | |
| if (self::$instance === null) { | |
| self::$instance = new self(); | |
| } | |
| return self::$instance; | |
| } | |
| private $db = null; | |
| private function __construct() {} | |
| public function connect($connection_string) | |
| { | |
| return $this->db = pg_connect($connection_string); | |
| } | |
| public function query($query) | |
| { | |
| return pg_query($this->db, $query); | |
| } | |
| } | |
| /* configuration */ | |
| $example_db = ExampleDatabase::getInstance(); | |
| $example_db->connect('dbname=testing'); | |
| /* usage */ | |
| $example_db = ExampleDatabase::getInstance(); | |
| $result = $example_db->query('SELECT * FROM users'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment