Reputation: 23
I have a little problem. I have make a config class which automaticlly return the value that i want.
usage example:
echo Config::get('database.host');
This returns localhost.
But if i have multiple vars then it returns the first i selected.
example:
echo Config::get('database.host');
echo Config::get('database.username');
echo Config::get('database.password');
echo Config::get('database.name');
all returns localhost.
here is my config class:
<?php
namespace App\Libraries;
class Config
{
private static $_config;
public static function set($config)
{
self::$_config = $config;
}
public static function get($var = null)
{
$var = explode('.', $var);
foreach ($var as $key) {
if (isset(self::$_config[$key])) {
self::$_config = self::$_config[$key];
}
}
return self::$_config;
}
public function __destruct()
{
self::$_config = null;
}
}
?>
i initialisate it like this:
Config::set($config);
the $config variable contains my entire config file:
<?php
$config = [
'database' => [
'host' => 'localhost',
'name' => 'dev',
'charset' => 'utf8',
'username' => 'root',
'password' => '1234'
]
];
?>
Hope you can help me guys :) (Sorry for bad english)
Upvotes: 1
Views: 686
Reputation: 360702
Well, yeah. The first time you call get()
, you destroy all the other config options:
Config::set($config); // sets your nested array
Config::get('foo.bar');
self::$_config = self::$_config['foo'];
^^^^^^^^--overwrite this
^^^^^^^^^^^^---with the foo sub value
self::$_config = self::$_config['bar'];
^^^^^^^^--overwrite the previous foo value
^^^^^^^---with bar's
Then the next time you call get(), you're not accessing your original $_config
array. you're accessing whatever value was retrieved with the LAST get() call.
You need to use a temp variable, e.g.
Config::get('foo.bar')
explode ...
$temp = self::$_config;
foreach(... as $key) {
$temp = $temp[$key];
}
return $temp;
Upvotes: 1