【发布时间】:2011-10-17 11:17:54
【问题描述】:
我只尝试连接到数据库 (MySQLi) 一次,但这样做时遇到了问题。
如何为整个脚本建立一个全局连接?有多个文件(index.php、/classes/config.class.php、/classes/admin.class.php 等)。
我尝试了以下方法:
在:config.class.php
public static $config = array();
public static $sql;
function __construct() {
// database
db::$config['host'] = 'localhost';
db::$config['user'] = '_';
db::$config['pass'] = '_';
db::$config['db'] = '_';
// connect
db::$sql = new mysqli(db::$config['host'], db::$config['user'], db::$config['pass'], db::$config['db']);
}
同样,在 config.class.php 中
public function contectToDatabase($sql){
$sql = new mysqli(db::$config['host'], db::$config['user'], db::$config['pass'], db::$config['db']);
$this->sql = $sql;
}
我使用具有以下代码的类:
$config = new db();
我真的很困惑我该怎么做。有人可以帮忙吗?
--- 编辑 --- 这是我的新 config.class.php 文件:
public static $config = array();
public static $sql;
private static $db;
private $connection;
public function __construct() {
// database
db::$config['host'] = '_';
db::$config['user'] = '_';
db::$config['pass'] = '_';
db::$config['db'] = '_';
// connect
$this->connection = new mysqli(db::$config['host'], db::$config['user'], db::$config['pass'], db::$config['db']);
}
function __destruct() {
$this->connection->close();
}
public static function getConnection() {
if($db == null){
$db = new db();
}
return $db->connection;
}
这就是我加载它的方式:
require_once("classes/config.class.php");
$config = new db();
$sql = db::getConnection();
但是,运行 real_escape_string 会导致以下错误:
Warning: mysqli::real_escape_string() [mysqli.real-escape-string]: Couldn't fetch mysqli in /home/calico/_/_.com/_/index.php on line 20
Warning: mysqli::query() [mysqli.query]: Couldn't fetch mysqli in /home/calico/_/_.com/_/index.php on line 28
【问题讨论】:
-
你可以使用singleton pattern
-
或者你可以学习依赖注入而不是使用singleton antipattern
-
是的……单身人士总是会引起激烈的争论。我只是提供意见和想法
-
有没有办法让连接作为每个类的全局变量?例如:我设置了一个名为 $sql 的全局变量,并将其设置为 $sql = new mysqli(db::$config['host'], db::$config['user'], db::$config[ '通过'], db::$config['db']);?我不想为每个班级重复数据库连接。
标签: php class mysqli global connect