-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?

2

2 Answers 2

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

Comments

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

Comments

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.