0

我需要一个将字符串作为参数的函数,然后检查是否设置了与该字符串命名相同的变量。

这有效...

$foo = 'foosuccess';
$property = 'foo';
if(isset($$property)){
echo $$property;
}

这不是,因为在 test() 中,$$property2 是错误的范围。

$huh = 'huhsuccess';
$huh = test("huh");
function test($property2){
    if(isset($$property2)){
        echo $$property2;
}
}

如何修复该函数,以便 $$property2 引用与调用者上下文相同的范围?那可能吗?

提前致谢....

4

4 回答 4

0

尝试这个:

$huh = 'huhsuccess';
test("huh");

function test($property2) {
    global $$property2;

    if(isset($$property2)) {
        echo $$property2;
    }
}
于 2011-09-16T00:26:57.290 回答
0
<?php
function test($s) 
{ 
  return isset($GLOBALS[$s]);
}
于 2011-09-16T00:32:15.677 回答
0

好的,我想我是出于我的目的想出来的(如果有人感兴趣的话……)

//uncomment to get success
//$huh = 'huhsuccess';
$huh = test($huh);

echo $huh;

function test(&$property2) {
   if(isset($property2)) {
       return $property2;
   } else {
       return 'not set!';
   }
}
die;
于 2011-09-16T17:33:47.277 回答
-1

这可以通过以下方式完成eval()

   $foo = 'foosuccess';
    $property = 'foo';
    if(eval('isset($'.$property.')'){
    echo $$property;
    }
于 2011-09-16T00:20:36.087 回答