简体   繁体   中英

how to apply a config file site-wide?

I'm modifying a website and I would like to add a config file for it so that when when moving the website to another server, I only need to change environment parameters like database information only once. But I don't know how to apply the config file for the whole site. I tried to use include_once() and make it global using keyword global but it only works in the current file. If I don't use define() to make these parameters as constant, are there any other way to achieve this? Thank you.

You can create a class Config and store your config parameters as Class Constants . Then include this class everywhere you need it, or use Autoload it .

class Config {
    const databaseUsername = "user123";
    const databasePassword = "pass456";
}

echo Config::databaseUsername;
echo Config::databasePassword;

But as in my experience, define() works perfectly well, unless you need to store more complicated data types (arrays for example).

To avoid include the config file everywhere, you could set auto_prepend_file in your PHP.ini , but I personally find this solution obscure, since it's not obvious for another developer working on your code that a PHP file is auto-included.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM