在PHP中使用类外的变量

Assuming that I have 3 PHP files:

  1. index.php:

    require('config.php');
    require('connect_db.php');
    new connect_db();
    
  2. config.php:

    $config['db_host'] = 'localhost';
    $config['db_username'] = 'root';
    $config['db_password'] = '';
    $config['db_name'] = 'my_db';
    
  3. connect_db.php:

    class connect_db{
        function __construct(){
           $this->conn = new mysqli($config['db_host'], $config['db_username'], $config['db_password'], $config['db_name']);
        }
    }
    

When I run above codes, I meet an error: "Undefined variable: config in....".
My question is: How can I use the $config variable inside "connect_db" class without including config.php file in connect_db.php file.

Thanks!

As mentioned in the comments, pass the $config variable into the constructor of the class.

new connect_db($config);

class connect_db{
    function __construct($config){
       $this->conn = new mysqli($config['db_host'], $config['db_username'], $config['db_password'], $config['db_name']);
    }
}

Hope it helps.

You can also add this line near the top of config.php and inside the __construct() function:

global $config;

Then they will be shared.

I would recommend choosing a better variable name than $config though. Perhaps something like $database_configuration, so you are less likely to use the same variable name in two places.