I'd like to use php eval() to identify potential parse errors. I'm aware of the dangers of eval, but this is a very limited use which will be fully validated beforehand.
I believe that in php 7 we should be able to catch a parse error, but it doesn't work. Here's an example:
$one = "hello";
$two = " world";
$three = '';
$cmdstr = '$three = $one . $tw;';
try {
$result = eval($cmdstr);
} catch (ParseError $e) {
echo 'error: ' . $e;
}
echo $three;
I'm trying to cause a parse error here to see if I can catch it, but when I run it, the error (undefined variable tw) appears as it usually would. It was not being caught.
Any ideas how to catch a parse error from eval?
Your code doesn't work as expected because, in PHP, an undefined variable doesn't trigger a parse error but a notice instead. Thanks to set_error_handler native function, you can convert a notice to error then catch it with this PHP 7 code:
<?php
set_error_handler(function($_errno, $errstr) {
// Convert notice, warning, etc. to error.
throw new Error($errstr);
});
$one = "hello";
$two = " world";
$three = '';
$cmdstr = '$three = $one . $tw;';
try {
$result = eval($cmdstr);
} catch (Throwable $e) {
echo $e; // Error: Undefined variable: tw...
}
echo $three;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With