PHP OOP 配置 Class
PHP OOP Config Class
我有个小问题。我做了一个配置 class 自动 return 我想要的值。
用法示例:
echo Config::get('database.host');
这 return 本地主机。
但如果我有多个变量,那么它 return 是我选择的第一个。
示例:
echo Config::get('database.host');
echo Config::get('database.username');
echo Config::get('database.password');
echo Config::get('database.name');
所有 returns 本地主机。
这是我的配置 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;
}
}
?>
我这样初始化它:
Config::set($config);
$config 变量包含我的整个配置文件:
<?php
$config = [
'database' => [
'host' => 'localhost',
'name' => 'dev',
'charset' => 'utf8',
'username' => 'root',
'password' => '1234'
]
];
?>
希望你们能帮助我:)
(抱歉英语不好)
嗯,是的。第一次调用 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
然后下次调用 get() 时,您将不会访问原始 $_config
数组。您正在访问通过上次 get() 调用检索到的任何值。
您需要使用临时变量,例如
Config::get('foo.bar')
explode ...
$temp = self::$_config;
foreach(... as $key) {
$temp = $temp[$key];
}
return $temp;
我有个小问题。我做了一个配置 class 自动 return 我想要的值。
用法示例:
echo Config::get('database.host');
这 return 本地主机。
但如果我有多个变量,那么它 return 是我选择的第一个。
示例:
echo Config::get('database.host');
echo Config::get('database.username');
echo Config::get('database.password');
echo Config::get('database.name');
所有 returns 本地主机。
这是我的配置 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;
}
}
?>
我这样初始化它:
Config::set($config);
$config 变量包含我的整个配置文件:
<?php
$config = [
'database' => [
'host' => 'localhost',
'name' => 'dev',
'charset' => 'utf8',
'username' => 'root',
'password' => '1234'
]
];
?>
希望你们能帮助我:) (抱歉英语不好)
嗯,是的。第一次调用 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
然后下次调用 get() 时,您将不会访问原始 $_config
数组。您正在访问通过上次 get() 调用检索到的任何值。
您需要使用临时变量,例如
Config::get('foo.bar')
explode ...
$temp = self::$_config;
foreach(... as $key) {
$temp = $temp[$key];
}
return $temp;