如何从包含脚本捕获编译错误


How capture compilation errors from an include script?

我想在函数中包含文件并使用ob_start()ob_get_contents()等将输出保存到文件中。

但是,如果该包含的文件中有错误,我希望:

  1. 让我的函数知道并捕获它(这样它就可以优雅地处理它)

  2. 不输出错误

set_error_handler会允许吗?

对于(大多数)非致命者,是的,set_error_handler可以抓住这些,你可以优雅地处理它们。

对于致命错误,请查看此问题的答案: PHP:自定义错误处理程序 - 处理解析和致命错误

现在,如果您

有兴趣防止简单的解析错误,如果您能够为 PHP 安装安装扩展,则可以使用 runkit 扩展runkit_lint_file。[附录编辑:即在包含文件之前对其进行检查。解析错误不可恢复。这也可以通过使用 -l 选项在命令行上运行 php 来完成。尽管根据主机的设置方式,您可能需要修改环境才能使命令行 php 选项正常工作。

这是一个命令行php的例子,我不确定它是否是一个很好的例子。从我的一个项目中翻录,并添加了一些评论。

/**
 * Lint and and retrieve the result of a file. (If lint is possible)
 * @param $file
 * @return Mixed bool false on error, string on success.
 */
function lint_and_include ($file) {
   if(is_readable($file)) {
      //Unset everything except PATH.
      //I do this to prevent CGI execution if we call
      //a CGI version of PHP.
      //Someone tell me if this is overkill please.
      foreach($_ENV as $key=>$value)
      {
         if($key == "PATH") { continue; }
         putenv($key);
      }
      $sfile = escapeshellarg($file);
      $output = $ret = NULL;
      //You could modify this to call mandatory includes to 
      //also catch stuff like redefined functions and the like.
      //As it is here, it'll only catch syntax errors.
      //You might also want to point it to the CLI php executable.
      exec("php -l $sfile", $output, $return);
      if($return == 0) {
         //Lint Okay
         ob_start();
         include $file;
         return ob_get_clean();
      }
      else {
         return false;
      }
   }
   else {
      return false;
   }
}

附加说明:在这种情况下,您的set_error_handler回调应记录它可以在某处捕获的错误,而不是输出它们。如果包含的任何代码可能会引发异常,您可能也希望使用 try-catch 块捕获这些异常。