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.

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. And yes, it's a fake name ;)
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']);
    }

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.