Lasse Vabe Rolstad
Lasse Vabe Rolstad

Reputation: 612

PHP - Require_once inside a class construct

When I use require_once and try to access the variable within the required file I get an error that the variable ($db) is undefined.

I have tried to place the require_once statement several diffrent places because I thought it might be variable scope issues, but at this point I try to call it within the constructor and the assign the value to a class variable.

My config class:

class Config {

    public $db;

    public function __construct() {
        require_once (BASE_DIR."config/DBConfig.php");
        $this->db = $db;
    }
}

The DBConfig file looks like this:

$db['default']['hostname'] = 'localhost'

Upvotes: 2

Views: 18396

Answers (2)

Luc Franken
Luc Franken

Reputation: 3014

I would do it differently and use dependency injection for this, giving you:

public function __construct((IDb)$Db) {
    $this->db=$Db;
}

That way it is way easier to test your software later, it is clear that this class needs some database object. Which makes your code also less coupled which seems to be a good architectural decision.

Also it would make it much easier to start using for example a different database class which saves you later time and effort.

Upvotes: 8

deceze
deceze

Reputation: 522250

It seems that since Require_once only gets the file the first time the class gets created the variable is only available in the first object i create.

Well then, change require_once to require. require_once is for including files that define classes and functions, that a) don't need to be included more than once and b) would cause errors if they were included more than once. If you always want to include the file, skip the _once.

Having said that, including a database configuration more than once is a sign of bad design.

Upvotes: 2

Related Questions