有没有一种方法来调用成立的功能之外,诸如使其成为一个全局变量的函数动态变量。
$a = 'test'
$b = 'cat'
$c = 'dog'
debug_vars(['a', 'b', 'c']);
function debug_vars( $arr ) {
$display = array();
foreach($arr AS $v) {
GLOBAL ${$v};
$display[$v] = $v;
}
print_r($display);
}
我想它显示[“一个” =>“测试”,“B” =>“猫”,“C” =>“狗”]的数组
你现在重新创建内置的compact
功能,已经做了你想要的东西:
$a = 'test' ;
$b = 'cat' ;
$c = 'dog' ;
print_r(compact('a','b','c'));
//Array ( [a] => test [b] => cat [c] => dog )
你快到了
$a = 'test';
$b = 'cat';
$c = 'dog' ;
debug_vars(['a', 'b', 'c']);
function debug_vars( $arr ) {
$display = array();
foreach($arr AS $v) {
GLOBAL ${$v};
$display[$v] = ${$v};
// ^---^--------------- use the global ?
}
print_r($display);
}
输出:
阵列([α] =>测试并[b] =>猫并[c] =>狗)
虽然这是按预期工作,我不建议你使用全局变量。这容易导致难以维护的代码。尝试使用比全局的另一种方法。
使用$GLOBALS[]
:
$display[$v] = $GLOBALS[$v];
- > http://php.net/manual/en/reserved.variables.globals.php
编辑:
使用global $$v
在其他的答案中提到,如果变量名称在本地使用可能会有副作用。
您可以使用variable variable
与$$
运营商。
<?php
$a = 'test';
$b = 'cat';
$c = 'dog';
debug_vars(['a', 'b', 'c']);
function debug_vars( $arr ) {
$debug = array();
foreach($arr AS $v) {
if ($v != 'debug') {
GLOBAL $$v;
$debug[$v] = $$v;
}
}
print_r($debug);
}