Using a PHP Class to Store Configuration
In a comment on my post listing 5 Tips for Writing Cleaner PHP Code, some good arguments were made against using constants to store configuration variables. The main arguments is that it pollutes the global namespace, which can lead to collisions when implementing other code, and the way it handles typos. This article demonstrates some of the ways constants can fail, and shows an alternative.
So here is how to store these constants in a class to avoid these problems. This puts the constants in their own namespace and prevent mistakes later on.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?php // Declaring your config class constants class Config { const DB_HOST = 'localhost', DB_USER = 'username', DB_PASS = 'password', ANOTHER_VAR = true; } echo Config::DB_HOST; // outputs localhost echo Config::USER; // PHP Fatal error if(Config::ANOTHER_VAR) { // do something } ?> |
That's all there is to it. Now all your constants are consolidated under one namespace and any typos will result in a fatal error. You can name the class whatever you want to be unique and avoid any collisions.

August 6th, 2010 - 12:01
is this really useful? is it not better to use XML or arrays, just tasking
August 7th, 2010 - 19:46
Well the use of a class is meant to solve the namespace issues. You could choose to use an array in the class, but the idea is the same. XML can be used for persistent storage, but you’d still need a place to store the data at runtime.
April 3rd, 2012 - 06:09
It would be better to put configuration information in a yaml file or xml file or even in a database.
April 3rd, 2012 - 10:31
Why? Parsing an external data structure or accessing a database would add lots of unnecessary overhead. You’d have to examine your requirements to determine if that would be worth it.
April 10th, 2012 - 20:55
If you want to make simplier then use $_ENV['DB_HOST']. If you want it to make more practical like you don’t wana or can’t step in ftp to the site then put configurations into editable form, yaml and xml nice but need to be parsed what is unnecessay most of time, use nativ php source
‘localhost’, ‘user’ => ‘me’ );
and call it with
function config( $ns )
{
return ( object ) include( ‘path/to/config/dir/’ . strtr( $ns, ‘.’, DIRECTORY_SEPARATOR ) . ‘.php’ );
}
and you can have something like this
config( ‘system.database’ )->host;
$dbconf = config( ‘system.database’ );
But Config\DB_HOST cool it’s age of namespaces anyway.
April 10th, 2012 - 20:57
it deleted the “\re\turn \arr\ay( ‘host’ =\>” without slashes ofc