I have multiple classes that use static methods. These functions connect to the database using
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_P
To elaborate on a mysqli singleton:
define('SERVER', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', 'password');
define('DATABASE', 'databaseName');
class mysqliSingleton
{
private static $instance;
private $connection;
private function __construct()
{
$this->connection = new mysqli(SERVER,USERNAME,PASSWORD,DATABASE);
}
public static function init()
{
if(is_null(self::$instance))
{
self::$instance = new mysqliSingleton();
}
return self::$instance;
}
public function __call($name, $args)
{
if(method_exists($this->connection, $name))
{
return call_user_func_array(array($this->connection, $name), $args);
} else {
trigger_error('Unknown Method ' . $name . '()', E_USER_WARNING);
return false;
}
}
}
You can then request the database connection by calling:
$db = mysqliSingleton::init();
You can then retrieve the database connection in your own objects:
class yourClass
{
protected $db;
public function __construct()
{
$this->db = mysqliSingleton::init();
}
}