Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Language Constructs and Statements

The eval construct

Reference for PHP eval(): run a string as PHP code, how it returns values and reports parse errors with ParseError, and safer alternatives.

eval() runs a string as PHP code. The string must be PHP code without the opening <?php tag, and it must end its statements with semicolons. It runs in the scope where it is called, so it can read and change local variables.

It is almost always the wrong tool. If any part of the string comes from a user, eval() is a remote code execution hole. Even with trusted input, code in strings cannot be analysed by editors, static analysers or opcode caches, and it is hard to debug.

PHP
$result = eval('return 6 * 7;');

Try it

PHP Return values and local scope

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Syntax errors throw ParseError

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
eval(string $code): mixed
Name Description
$code PHP code to run, without <?php ... ?> tags. Must be valid statements, including the final semicolon.

Return value: null unless the code calls return, in which case that value is returned.

Exceptions: a syntax error throws ParseError (PHP 7+; before PHP 7 eval() returned false). Other errors and exceptions in the evaluated code behave as in normal code and can be caught.

Usage notes

  • Never pass user input. Escaping is not a reliable defence. Use a lookup table, a match, a parser or a dedicated expression library.
  • Scope. The code sees and changes the variables of the surrounding scope, which makes side effects easy to miss.
  • A language construct, not a function. It cannot be called through a variable or callback, and because it is a construct, disable_functions in php.ini cannot turn it off (the Suhosin patch could, but is long gone).
  • Performance. The string is compiled on every call.
  • Better options. Closures and callables for behaviour, include for files, templates for output, and match or arrays for dispatch.
  • Errors report odd locations. Messages mention eval()'d code and a line number inside the string.