函数检查isset的php范围问题


php scope issue for function checking isset

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

这很有效。。。

$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引用与调用方上下文相同的范围?这可能吗?

提前感谢。。。。

试试这个:

$huh = 'huhsuccess';
test("huh");
function test($property2) {
    global $$property2;
    if(isset($$property2)) {
        echo $$property2;
    }
}
<?php
function test($s) 
{ 
  return isset($GLOBALS[$s]);
}

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

//uncomment to get success
//$huh = 'huhsuccess';
$huh = test($huh);
echo $huh;
function test(&$property2) {
   if(isset($property2)) {
       return $property2;
   } else {
       return 'not set!';
   }
}
die;

这可以用eval():完成

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