[英]PHP OOP Config Class
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: $ config变量包含我的整个配置文件:
<?php
$config = [
'database' => [
'host' => 'localhost',
'name' => 'dev',
'charset' => 'utf8',
'username' => 'root',
'password' => '1234'
]
];
?>
Hope you can help me guys :) (Sorry for bad english) 希望你能帮助我:)(对不起,英语不好)
Well, yeah. 好吧,是的 The first time you call
get()
, you destroy all the other config options: 第一次调用
get()
,将销毁所有其他配置选项:
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. 然后,下次调用get()时,就不会访问原始的
$_config
数组。 you're accessing whatever value was retrieved with the LAST get() call. 您正在访问通过LAST get()调用检索到的任何值。
You need to use a temp variable, eg 您需要使用一个临时变量,例如
Config::get('foo.bar')
explode ...
$temp = self::$_config;
foreach(... as $key) {
$temp = $temp[$key];
}
return $temp;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.