eval() Without Try

The eval() command throws an error in case of unparsable PHP code. This error can be caught, to handle gracefully the situation, with a try-catch structure.

It is recommended to always use try-catch when dealing with eval().

It is possible to differentiate a parse error in the host code from a parse error in the eval() string with the error message: when it is in the eval() string, the error message mention eval: Parse error: syntax error, unexpected identifier "a" in file.ph : eval()'d code on line 1.

PHP code

<?php

try {
    eval('A = 1');
} catch (Error $e) {
    echo $e->getMessage();
}

?>

Before

Parse error: syntax error, unexpected '='

After

syntax error, unexpected token "="

PHP version change

This behavior changed in 7.0