Axis
Axis

Reputation: 49

How to make a config class file in PHP

Is it possible to make a configuration class in PHP?
First you need to get the $GLOBALS['config'] then the key that has been called (for example):
echo Config::get('database/main/username');

Then every 'key' is exploded (a PHP function) by a delimiter of ' / ', then every 'key' again is added to the main key. The main key is $GLOBALS['config'] which is having the whole array of configurations.


So, every key should be defined (trying foreach) and add a 'count' to know what is the count of the array is


My codes so far:

<?php 
    $GLOBALS['config'] = array(
        "database" => array(
            "username" => 'root',
            "password" => '',
            'host' => '127.0.0.1',
            'name' => 'thegrades'
        ),
    );
    class Config
    {
        public static function get($key = null)
        {
            $count = 0;
            $key = explode("/", $key);
            if(count($key) > 1){
                $mainkey = $GLOBALS['config'];
                foreach($key as $value){                    
                    $mainkey .= [$key[$count]];
                    $count++;
                }
            }
            return $mainkey;
        }
    }
    var_dump(Config::get('database/host'));
 ?>

Upvotes: 1

Views: 1199

Answers (1)

JustOnUnderMillions
JustOnUnderMillions

Reputation: 3795

On way to rome, refactor this and take what you need.

<?php 
$GLOBALS['config'] = array(
    "database" => array(
        "username" => 'root',
        "password" => '',
        'host' => '127.0.0.1',
        'name' => 'thegrades'
    ),
);
class Config
{
    public static function get($key = null)
    {
        $keys = explode("/", $key);
        $tmpref = &$GLOBALS['config'];
        $return = null;
        while($key=array_shift($keys)){
            if(array_key_exists($key,$tmpref)){
              $return = $tmpref[$key];
              $tmpref = &$tmpref[$key];
            } else {
              return null;//not found
            }
        }
        return $return;//found
    }
}
var_dump(Config::get('database/host'));//127.0.0.1
?>

Upvotes: 2

Related Questions