我有一个允许PDO连接的类,它自己设置。当我想使用连接时,我可以使用:
$db = $factory->create('db');
但是,我希望能够做到:
global $db;
任何时候我想使用数据库。
这行得通吗?
$db = function(){
$con = $factory->create('db');
return $con;
};
global $db;
这样,我可以关闭连接,然后在任何时候再次打开它。例:
global $db;
$db->close();
// Re-open
global $db;
或者我怎么可能这样做?参考资料将不胜感激,因为我已经搜索了很多。
提前谢谢。
@Devon评论部分解释了作用域以及如何实现这一点。
为了使其正常工作,您只需执行以下操作:
$db = $factory->create('db');
// close it
$db = null;
// re-open it
$db = $factory->create('db');
或者这个:
function db(){
$db = $factory->create('db');
global $db;
}
db();
$db->.....