是否可以使用 ob_start()/ob_clean/ob_flush() 在 PHP 中进行错误处理?


is it acceptable to use ob_start()/ob_clean/ob_flush() to do error handling in PHP?

下面这样在 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();?>

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

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

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

<?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