PHP eval() Function
The PHP eval() function is not really a function, but a language construct and used to evaluate a given string as PHP code.
The string must be valid PHP code and must end with semicolon. A return statement will immediately terminate the evaluation of the code.
The code will be executed in the scope of the code calling this function. Hence, any variables defined or changed in the call will remain visible after it terminates.
Syntax
eval(phpcode)
Parameters
phpcode |
Required. Specify the valid PHP code to be evaluated. The code must NOT be wrapped in opening and closing PHP tags. |
Return Value
Returns null unless return is called in the evaluated code, in which case the value passed to return is returned. As of PHP 7, if there is a parse error in the evaluated code, eval() throws a ParseError exception. Before PHP 7, in this case eval() returned false and execution of the following code continued normally. It is not possible to catch a parse error in eval() using set_error_handler().
Example: eval() example - simple text merge
The example below shows the usage of eval() function.
<?php $string = 'nice'; $time = 'spring'; $str = 'This is a $string $time day.'; echo $str. "\n"; eval("\$str = \"$str\";"); echo $str. "\n"; ?>
The output of the above code will be similar to:
This is a $string $time day. This is a nice spring day.
❮ PHP Miscellaneous Reference