我通过PDO访问我的MySQL数据库.我正在设置对数据库的访问权限,我的第一次尝试是使用以下内容:
我想到的第一件事是global:
$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'root', 'pwd');
function some_function() {
global $db;
$db->query('...');
}
Run Code Online (Sandbox Code Playgroud)
这被认为是一种不好的做法.一点点搜索后,我结束了与Singleton模式,其
"适用于需要单个类实例的情况."
根据手册中的示例,我们应该这样做:
class Database {
private static $instance, $db;
private function __construct(){}
static function singleton() {
if(!isset(self::$instance))
self::$instance = new __CLASS__;
return self:$instance;
}
function get() {
if(!isset(self::$db))
self::$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'user', 'pwd')
return self::$db;
}
}
function some_function() {
$db = Database::singleton();
$db->get()->query('...');
}
some_function();
Run Code Online (Sandbox Code Playgroud)
当我能做到这一点时,为什么我需要相对较大的课程呢?
class Database {
private static $db;
private function __construct(){}
static function get() …Run Code Online (Sandbox Code Playgroud)