Calling user defined functions in PHP eval()

痞子三分冷 提交于 2019-12-12 21:08:58

问题


I was been doing a php testing which uses eval() function, but it seems that eval() can't call user defined functions properly.

Please see my example:

function equals($a,$b){  
        if ($t == $r){  
        return true;  
        }  
    else{  
                throw new Exception("expected:<".$r."> but was:<".$t.">");  
    }  
}
eval("$test = 1;");  
try{  
    echo eval("equals($test,1);");  
}  
catch (Exception $e) {  
    echo $e->getMessage();  
}  

but what I have received is always like "expected:<1> but was:<>", but if I have do an

echo $test;

I can get 1.

I have tried changing $ to \$ by following the PHP eval() Manual, but it seems to break the eval function. (http://php.net/manual/en/function.eval.php)

So I am a bit of stack now, can someone help me with the problem. Thank you very much.


回答1:


you are missing return

echo eval("return equals(\"$test\",1);");

From PHP manual

eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. If there is a parse error in the evaluated code, eval() returns FALSE and execution of the following code continues normally.

eval()

avoid to use eval() as @Delan suggested.




回答2:


Don't use eval().

If you want to call a user-defined function, say, derp, with the name at runtime:

$functionName = 'derp';
$functionName(argument1, argument2, ...);

Notice how I prefixed functionName with $ so I'm not calling functionName but rather, derp.

So, for your example, calling a user-defined function, equals:

$functionName = 'equals';
$functionName($test, 1);



回答3:


If you want to use eval, I believe the problem is that you need to escape both $ (it wasn't clear from your post if you did that). So your code would read

    function equals($a,$b){           
if ($t == $r){          
 return true;           
}      
 else
{                   
throw new Exception("expected:<".$r."> but was:<".$t.">");       
}  
 } 
eval("\$test = 1;");   
try{       
echo eval("equals(\$test,1);");   
}   
catch (Exception $e) {      
 echo $e->getMessage();  
 }  

You could also use single quotes for your eval strings which do not evaluate variables. As others have pointed out, though, there may be better ways of doing this.



来源:https://stackoverflow.com/questions/5167961/calling-user-defined-functions-in-php-eval

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!