How to create global configuration file?

后端 未结 3 1034
-上瘾入骨i
-上瘾入骨i 2021-01-12 05:02

Is there any possibility to create a configuration file with global variables that are visible inside the class? Something similar to this:

config.php:



        
3条回答
  •  一整个雨季
    2021-01-12 05:57

    Your problem is that you are trying to use an expression in the class definition here:

    class DB
    {
        private $_config = array($config['host_address'], ...
    

    That is syntactically incorrect (you can only use constant values for that), and I wouldn't expect it to locate the intended scope there. What you should do instead is initialize this property in the construtor instead:

    class DB
    {
        private $_config;
    
        function __construct() {
            global $config;
            $this->_config = array($config['host_address'], $config['username'], $config['password'], $config['name']);
        }
    

    Or even lazier, just use include('config.php'); in place of the global $config alias. That way your config script will extract $config as local variable within the constructor, which is all you need.

提交回复
热议问题