配置类-从函数字符串参数中获取配置数组


Configuration class - Get configuration array from the function string argument

我有一个这样的函数:

$conf = array ('test_value' => 1, 'test_value2' => 2);
function GetValueArray($array, $value)
{
     return $array[$value];
}

我使用这个函数从数组中接收一个值。我的问题是我不能像这样使用这个函数:

GetValueArray('conf', 'test_value');

我怎么能转换'conf'到真正的数组命名conf接收我的'test_value'?

因为函数有它们自己的作用域,所以一定要将你正在查看的变量"全球化"。

但是正如Rizier123所说,你可以在变量周围使用括号来动态地获取/设置变量。

<?php
$conf = array ('test_value' => 1, 'test_value2' => 2);
function GetValueArray($array, $value)
{
  global ${$array};
  return ${$array}[$value];
}
echo GetValueArray('conf', 'test_value'); // echos '1'
echo GetValueArray('conf', 'test_value2'); // echos '2'

?>