全局变量 - 数据库连接?

Pet*_*ter 8 php mysqli global class connect

我只想连接一个数据库(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']);
}
Run Code Online (Sandbox Code Playgroud)

再次,在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;
}
Run Code Online (Sandbox Code Playgroud)

我使用以下代码的类: $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;
}
Run Code Online (Sandbox Code Playgroud)

这就是我加载它的方式:

require_once("classes/config.class.php");
$config = new db();
$sql = db::getConnection();
Run Code Online (Sandbox Code Playgroud)

但是,运行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
Run Code Online (Sandbox Code Playgroud)

meg*_*lop 14

就个人而言,我使用的是单身类.像这样的东西:

<?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;
    }
}

?>
Run Code Online (Sandbox Code Playgroud)

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