简体   繁体   English

如何从类访问配置文件中的数组

[英]how to access an array in a config file from a class

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']);
    }
}

In the example above I get this error: 在上面的示例中,我收到此错误:

Notice: Undefined variable: database in C:\\wamp\\www\\career\\inc\\controller.php on line 11 注意:未定义的变量:第11行的C:\\ wamp \\ www \\ career \\ inc \\ controller.php中的数据库

How can I get access to the array I have in config.php ? 我怎样才能访问config.php的数组? It contains the $database array. 它包含$database数组。

Better is to inject the information: 最好是注入以下信息:

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

Or perhaps even better just pass the database instance directly: 甚至更好的方法是直接传递数据库实例:

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

What PeeHaa said stands. PeeHaa所说的是正确的。 Another way to do it would be using a singleton class for your config options. 另一种方法是对配置选项使用单例类。

If you still want to do it your way, I assume $database is global, so your constructor should be: 如果您仍然希望按照自己的方式进行操作,那么我假设$ database是全局的,那么您的构造函数应为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM