Reputation: 6389
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.
Upvotes: 0
Views: 75
Reputation:
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']);
}
Upvotes: 1
Reputation: 72672
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
Upvotes: 3