-1

So I have a config file, config_inc.php:

<?php
static $config = Array();
$config['dbHost'] = 'localhost';
$config['dbPass'] = '';
$config['dbUser'] = 'root';
$config['dbName'] = 'recipes_comments';
?>

And then I have a controller which is supposed to load these variables using require_once:

require_once "config_inc.php";
class Controller {
public function regUser() {
echo $config['dbHost'];
}
}

I tried to find posts with similar errors, but could not find one that provides a solution that fixes this.

When I try to echo a variable defined in config_inc.php as shown above, I get an error that config is undefined.

My question: Why is config not defined in Controller and what's the proper way to do this?

tereško
  • 58,060
  • 25
  • 98
  • 150
Mark
  • 1
  • 1
  • 1
  • 1
    possible duplicate of [PHP - Require\_once inside a class construct](http://stackoverflow.com/questions/9112664/php-require-once-inside-a-class-construct) – Jay Blanchard Oct 09 '14 at 16:27
  • [Similar question](http://stackoverflow.com/questions/6275931/null-variable-in-php-class). – Ja͢ck Oct 10 '14 at 06:15

2 Answers2

2

config is not defined in Controller because it's not global.

The Bad Way You first have to replace static by global in your config file, then add global $config at the beginning of your function.

The proper Way Don't use global in php. Instead, pass your $config array in the constructor of your class, or add it in an other way. For example

require_once "config_inc.php";

class Controller {
  private $config;
  public function regUser() {
    echo $this->config['dbHost'];
  }
  public function __construct($config)
  { 
    $this->config = $config;
  }
}

$controller = new Controller($config);
$controller->regUser();
Asenar
  • 6,732
  • 3
  • 36
  • 49
-2

This is a scope issue. You are trying to access to a variable that your class can't see from his scope.

$config is a global variable in your code. That mean, he exist in the global scope.

try this:

require_once "config_inc.php";
class Controller {
    public function regUser() {
        echo $GLOBALS['$config']['dbHost'];
    }
}
José María
  • 790
  • 13
  • 24