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.