全局变量-数据库连接


Global Variable - database connection?

我正在尝试连接到数据库(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

我个人使用单例类。像这样:

<?php
class Database {
    private static $db;
    private $connection;
    private function __construct() {
        $this->connection = new MySQLi(/* credentials */);
    }
    function __destruct() {
        $this->connection->close();
    }
    public static function getConnection() {
        if (self::$db == null) {
            self::$db = new Database();
        }
        return self::$db->connection;
    }
}
?>

然后在我需要的地方使用$db = Database::getConnection();