php
2013-02-20 33 views 0 likes 
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']); 
    } 
} 

訪問陣列的配置文件在上面的例子中我得到這個錯誤:如何從一個類

Notice: Undefined variable: database in C:\wamp\www\career\inc\controller.php on line 11

?我怎樣才能訪問陣列我有config.php?它包含$database陣列。

回答

3

更好的是注入的信息:

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 
+0

感謝。是的,這是一個假的名字;) – 2013-02-20 09:52:44

1

什麼PeeHaa說看臺:

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 

甚至更​​快只需直接通過數據庫實例。另一種方法是使用singleton類作爲配置選項。

如果你還想做你的方式,我想$數據庫是全球性的,所以你的構造應該是:

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

感謝您的信息。 – 2013-02-20 09:55:09

+0

[在類中使用全局變量](http://stackoverflow.com/questions/11923272/use-global-variables-in-a-class/11923384#11923384) – PeeHaa 2013-02-20 09:59:22

相關問題