Calling user defined functions in PHP eval()
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.
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);
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.
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.
精彩评论