简体   繁体   English

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

[英]Configuration class - Get configuration array from the function string argument

I have a function like this: 我有一个这样的功能:

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

Im using this function to receive a value from an array. 我正在使用此函数从数组接收值。 My problem is that i cannot use this function like this: 我的问题是我不能使用这样的功能:

GetValueArray('conf', 'test_value');

How could i convert 'conf' to the real array named conf to receive my 'test_value'? 我如何将“ conf”转换为名为conf的真实数组以接收“ test_value”?

Because functions have their own scope, be sure to 'globalize' the variable that you're looking into. 由于函数有其自身的作用域,因此请确保“全局化”要查找的变量。

But as Rizier123 said, you can use brackets around a variable to dynamically get/set variables. 但是正如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'


?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM