Page 1 of 1

How to use php class to store configuration

Posted: Sun Feb 28, 2010 10:59 pm
by Neo
This puts the constants in their own namespace and prevent mistakes later on.

Code: Select all

<?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.