php使用一次需要记录错误

时间:2013-06-17 15:54:32

标签: php logging error-handling require-once

我在php脚本中使用require_once,我想知道编写代码的正确方法,以便在失败时处理错误。

目前,我只使用require_once('included_file.php'); 我在想这个:

if (!@require_once('included_file.php')){
//log error, print nice error message, and exit;
}

这是“良好做法”,还是有不同的/更好的方法来做到这一点。我已经阅读了这个页面(http://us3.php.net/manual/en/language.operators.errorcontrol.php)并看到了使用OR DIE,但我不确定最好的方法。

谢谢!

4 个答案:

答案 0 :(得分:3)

如果require*调用失败,脚本会立即停止,不会执行其他代码。您无法正常处理require_once错误。如果PHP进程无法成功,您可以配置 Web服务器以使用错误页面来处理它。否则,您必须使用基本上显示的代码,但使用include_once。您不应使用@来抑制产生的错误,而只是关闭错误 display ,以便记录错误。

说了这么多,您应该使用require*来运行必需的文件。您甚至不应该编写任何其他代码来处理这些文件不可用的情况,因为这意味着您的应用程序处于完全不可用的状态。如果所有必需文件都不存在,则甚至不应将应用程序部署到生产服务器,因此不需要任何正常的错误处理。你真的想要打击你的一些错误;缺少关键文件就是其中之一。

答案 1 :(得分:1)

require_once会触发compilation错误。因此,执行将暂停,自定义日志记录将无法进行

请参阅require http://www.php.net/manual/en/function.require.php

的文档
require is identical to include except upon failure it will also produce a fatal
E_COMPILE_ERROR level error. In other words, it will halt the script whereas
include only emits a warning (E_WARNING) which allows the script to continue.

答案 2 :(得分:1)

使用required_once包含文件意味着如果脚本无法加载给定文件,脚本将停止执行。在某些标准上使用require_once是很好的。它取决于包含文件的重要性。

答案 3 :(得分:0)

嗯 - 最初的想法是PHP已经处理了你想要的2/3 - 记录致命错误并在所需文件加载失败时退出。听起来真正的问题只是你想要一些“漂亮”的错误页面 - 这个页面有一个很好的演练如何设置它 - http://papermashup.com/create-an-error-page-to-handle-all-errors-with-php/