Webdesign,code & ...stuff!

Jul 30, 2009

Execute String as a PHP Code

I've ran into a problem where I want to execute a php string stored in a php variable

eg. $string='myfunction();';

I want a PHP function to execute
$string and return its OUTPUT (not its value which is a string).
I think about something like exec() or php_exec so I googled it and ended up with shell_exec() blah,blah,blah. My head is messed up until I found this very short php built-in function:

eval() - Evaluate a string as a php code . Very cool...
<?
function myfunction($val){
echo
$val;
}
$str='myfunction("Reynold Salceda");';
eval(
$str); //returns: Reynold Salceda
?>

More samples here:
http://uk2.php.net/manual/en/function.eval.php

0 comments: