问题
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'?
回答1:
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.
<?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'
?>
来源:https://stackoverflow.com/questions/32640424/configuration-class-get-configuration-array-from-the-function-string-argument