0
require_once($_SERVER["DOCUMENT_ROOT"] . 'config.php');

class stuff{

    public $dhb;

    public function __construct(){
        $dbh = new PDO('mysql:host=' . $database['host'] . ';dbname=' . $database['dbname'] . '', $database['user'], $database['password']);
    }
}

在上面的示例中,我收到此错误:

注意:未定义变量:第 11 行 C:\wamp\www\career\inc\controller.php 中的数据库

如何访问我拥有的数组config.php?它包含$database数组。

4

2 回答 2

3

更好的是注入信息:

class stuff{

    public $dhb;

    public function __construct($database){
        $dbh = new PDO('mysql:host=' . $database['host'] . ';dbname=' . $database['dbname'] . '', $database['user'], $database['password']);
    }
}

require_once($_SERVER["DOCUMENT_ROOT"] . 'config.php');
$stuff = new stuff($database); // really hope this is a fake name

或者甚至更好的是直接传递数据库实例:

class stuff{

    public $dhb;

    public function __construct($dbh){
        $this->dbh = $dbh;
    }
}

require_once($_SERVER["DOCUMENT_ROOT"] . 'config.php');
$dbh = new PDO('mysql:host=' . $database['host'] . ';dbname=' . $database['dbname'] . '', $database['user'], $database['password']);
$stuff = new stuff($dbh); // really hope this is a fake name
于 2013-02-20T09:27:18.757 回答
1

PeeHaa 所说的站得住脚。另一种方法是为您的配置选项使用单例类。

如果您仍想按照自己的方式进行操作,我假设 $database 是全局的,因此您的构造函数应该是:

public function __construct(){
        global $database;
        $dbh = new PDO('mysql:host=' . $database['host'] . ';dbname=' . $database['dbname'] . '', $database['user'], $database['password']);
    }
于 2013-02-20T09:47:01.810 回答