如何在 PHP 中制作配置 class 文件
How to make a config class file in PHP
是否可以在 PHP 中进行配置 class?
首先,您需要获取 $GLOBALS['config'] 然后是已调用的密钥(例如):
echo Config::get('database/main/username');
然后每个 'key' 被分隔符“/”展开(一个 PHP 函数) ,然后每个 'key' 再次添加到主键。主键是 $GLOBALS['config']
,它具有整个配置数组。
因此,应该定义每个键(尝试 foreach)并添加一个 'count' 以了解数组的计数是
到目前为止我的代码:
<?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'));
?>
在去罗马的路上,重构它并拿走你需要的东西。
<?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
?>
是否可以在 PHP 中进行配置 class?
首先,您需要获取 $GLOBALS['config'] 然后是已调用的密钥(例如):echo Config::get('database/main/username');
然后每个 'key' 被分隔符“/”展开(一个 PHP 函数) ,然后每个 'key' 再次添加到主键。主键是 $GLOBALS['config']
,它具有整个配置数组。
因此,应该定义每个键(尝试 foreach)并添加一个 'count' 以了解数组的计数是
到目前为止我的代码:
<?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'));
?>
在去罗马的路上,重构它并拿走你需要的东西。
<?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
?>