【问题标题】:Output buffer error handling输出缓冲区错误处理
【发布时间】:2015-09-20 21:20:54
【问题描述】:

让我们假设一个简单的 sn-p 用于模板并且是using output control (ob)

public function capture($file, array $args = array())
{
    extract($args, EXTR_SKIP);

    ob_start();

    require $file; //'foo.php'

    return ob_get_clean();
}

foo.php 有错误(由error handlershutdown handler 处理)

<?php

echo "before";
echo $someVariable; //$someVariable is undefined here
echo "after";

输出

before <- would like to avoid
some message from the error handler

问题:是否有可能避免文件出错时的任何输出?

是的,

【问题讨论】:

  • 你能不能只使用 ob_get_clean(),我在生产中使用它来避免出现在屏幕上的错误

标签: php error-handling output output-buffering


【解决方案1】:

如果您使用关闭处理程序而不是错误处理程序,它可以清除输出,因为错误处理程序只能清除它之前的输出,因此在它之后输出的任何内容仍然会呈现。

<?php

function error_handler()
{
    if(error_get_last()) {
        ob_get_clean();
        echo 'An error has occured.';
    }
}

register_shutdown_function('error_handler');

function capture()
{
    ob_start();

    require 'foo.php';

    return ob_get_clean();
}

echo capture();

// foo.php
<?php

echo 'before';
echo $variable;
echo 'after';

?>

这只会输出“发生错误。”

但是使用 set_error_handler 它将输出 'An error has occurred.after' 除非您添加 DIE() 或类似于错误处理程序的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    • 2017-05-12
    • 2014-08-29
    • 2017-10-01
    • 1970-01-01
    相关资源
    最近更新 更多