2 回答

TA貢獻1829條經驗 獲得超7個贊
您的代碼無法按預期工作,因為在 PHP 中,未定義的變量不會觸發解析錯誤,而是會觸發通知。感謝set_error_handler本機函數,您可以將通知轉換為錯誤,然后使用以下 PHP 7 代碼捕獲它:
<?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;

TA貢獻2039條經驗 獲得超8個贊
您的 PHP 代碼會拋出“Notice”類型的錯誤,并且這些錯誤無法由 try..catch 塊處理。您必須使用 PHP 的set_error_handler方法來使用自己的錯誤處理程序。閱讀該文檔,您就會明白該怎么做。如果您想要一個如何操作的示例,那么:
<?php
function myErrorHandler($errno, $errstr)
{
? ? switch ($errno) {
? ? ? ? case E_USER_ERROR:
? ? ? ? ? ? die("User Error");
? ? ? ? ? ? break;
? ? ? ? default:
? ? ? ? ? ? die("Your own error");
? ? ? ? ? ? break;
? ? }
? ? /* Don't execute PHP internal error handler */
? ? return true;
}
$err = set_error_handler("myErrorhandler");
$one = "hello";
$two = " world";
$three = '';
$cmdstr = '$three = $one . $tw;';
$result = eval($cmdstr);
echo $three;
?>
- 2 回答
- 0 關注
- 176 瀏覽
添加回答
舉報