Tony
Tony

Reputation: 253

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.

Upvotes: 0

Views: 285

Answers (1)

Tchoupi
Tchoupi

Reputation: 14691

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.

Upvotes: 2

Related Questions