Skip to content

Instantly share code, notes, and snippets.

@khamer
Last active August 8, 2022 09:41
Show Gist options
  • Select an option

  • Save khamer/64cd02f06b52992ec59a to your computer and use it in GitHub Desktop.

Select an option

Save khamer/64cd02f06b52992ec59a to your computer and use it in GitHub Desktop.
Example of a Singleton Class
<?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