Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling user defined functions in PHP eval()

Tags:

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.

like image 306
wgx731 Avatar asked Mar 14 '26 14:03

wgx731


1 Answers

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);
like image 59
Delan Azabani Avatar answered Mar 16 '26 03:03

Delan Azabani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!