2011-10-17 62 views
6

我想连接到一个数据库(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();

我真的很困惑a我怎么做到这一点。谁能帮忙?

---编辑--- 这是我的新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 
+1

你可以使用[singleton pattern](http://en.wikipedia.org/wiki/Singleton_pattern) – knittl

+1

或者你可以学习依赖注入而不是使用[singleton antipattern](http://stackoverflow.com/ question/4595964/who-needs-singletons/4596323#4596323) – Gordon

+1

是的......单身人士总是引发热议。我只是提供输入和想法 – knittl

回答

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

?> 

就用$db = Database::getConnection();,无论我需要它。

+0

你的Singleton可以被序列化和克隆,这意味着它不能确保只有一个实例。 – Gordon

+0

好吧,我已将它添加到配置类,并试图加载它。但是,有错误(请参阅主文章,在---编辑---行下)。任何想法什么是错的? – Peter

+1

@Peter不要将它添加到另一个类。这是一个单独的类,应该是独立的,不应该有公共的构造函数。只要使用'$ db = Database :: getConnection();'就可以在任何你需要的地方获得一个开放的MySQLi实例。 – megaflop