How to use php class to store configuration

Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to use php class to store configuration

Post by Neo » Sun Feb 28, 2010 10:59 pm

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.
Post Reply

Return to “PHP & MySQL”