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

In the example above I get this error:

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

How can I get access to the array I have in config.php? It contains the $database array.

Paul Dessert
  • 6,363
  • 8
  • 47
  • 74

2 Answers2

3

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
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
1

What PeeHaa said stands. 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:

public function __construct(){
        global $database;
        $dbh = new PDO('mysql:host=' . $database['host'] . ';dbname=' . $database['dbname'] . '', $database['user'], $database['password']);
    }
  • [Use global variables in a class](http://stackoverflow.com/questions/11923272/use-global-variables-in-a-class/11923384#11923384) – PeeHaa Feb 20 '13 at 09:59