【问题标题】:is it acceptable to use ob_start()/ob_clean/ob_flush() to do error handling in PHP?使用 ob_start()/ob_clean/ob_flush() 在 PHP 中进行错误处理是否可以接受?
【发布时间】:2015-05-09 16:00:12
【问题描述】:

可以像下面这样在 php 中进行错误处理吗?我对ob_start()/ob_clean()/ob_flush()不是很熟悉,所以我想知道使用它们有什么不好的影响吗?例如,它们会影响性能吗?

<?php 
    function custorErr()
    {
        ob_clean();
        //echo error message and some other error handling...
        die();
    }
    set_error_handler("custorErr");
    ob_start();

?>
<!doctype html>
<!-- html here -->
<html>
    <head>
    </head>
    <body>
        demo
    </body>
</html>
<?php ob_flush();?>

如果这不是最佳做法,那么有没有更好的方法在出现错误时清除所有页面内容?

【问题讨论】:

  • 我实际上并不确定这一点。好问题!但我想在使用 ob_start() 之前放置 set_error_handler 是个好主意
  • @bestprogrammerintheworld 我按照你的建议编辑了这个问题中的代码

标签: php error-handling


【解决方案1】:

我想你的方法会很好用,如果你想反复使用它,我认为你的方法是最好的。

另一种选择是将缓冲部分放在try/catch-block 中。如果出现问题,然后清理输出缓冲区。如果只是你想检查这个错误的一个位置,我相信这种方法会更好。

<?php 
try {
    ob_start();
    ?>
    <!doctype html>
    <!-- html here -->
    <html>
        <head>
        </head>
        <body>
            demo
        </body>
    </html>
    <?php
    ob_flush();
}
catch {Exception $e) {
    ob_end_clean(); //OR ob_clean();
    echo 'error is ' . print_r($e, true);
}

一些关于清理输出缓冲的文档:

http://php.net/manual/en/function.ob-end-clean.php

http://php.net/manual/en/function.ob-clean.php

【讨论】:

    猜你喜欢
    • 2017-10-01
    • 2013-10-08
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    相关资源
    最近更新 更多