dqpfkzu360216 2013-02-14 13:52
浏览 31
已采纳

发生错误时如何防止ob_start()输出?

Please, consider the following example:

template.php:

<?php

echo $vars['arr'];

echo " -------- ";

echo $vars['obj'];

?>

test.php:

<?php
$file = "template.php";
$vars = array( 'arr' => array(), 'obj' => new StdClass() );  

var_dump( json_encode($vars)  );  

function loadFile($file, $vars)
{
    try 
    {
        if (is_array($vars) && !empty($vars)) {
            extract($vars);
        }

        ob_start();
        include $file;
        return ob_get_clean();
    } 
    catch (Exception $e) 
    {
        return false;
    }
}

loadFile($file, $vars);

?>

This code will output:

string(19) "{"arr":[],"obj":{}}"
PHP Catchable fatal error:  Object of class stdClass could not be converted to string in template.php

The problem here is, in the template.php I am considering $vars to be an array() however 1 of the elements is an Object as you can see from the json output.

Adding a simple checking in the template to verify if the ekement is an array or not would solve the problem, however I would need to this to multiple elements, elements, so, not very good =) so, I trying to find a way to prevent the error in the moment of binding the template and $vars.

Thank you

  • 写回答

4条回答 默认 最新

  • dongmo9996 2013-02-14 14:03
    关注

    simply turn error_reporting off while parsing:

    $old_level = error_reporting(0); // no errors, preserve old error reporting level
    ob_start();
    include $file;
    $content = ob_get_clean();
    error_reporting($old_level); // reset error reporting level
    return $content;
    

    Note: This will only hide errors that aren't very critical.

    In order to catch a Catchable Fatal Error, see this question: How can I catch a "catchable fatal error" on PHP type hinting?

    You need to register an error handler using set_error_handler:

    function handleError($errno, $errstr, $errfile, $errline) {
      // handle error
    
      // return true, so the normal php handler doesn't get called
      return true;
    }
    set_error_handler('handleError');
    

    If you want to integrate you handler cleanly into other code which also sets error_handlers, you might consider restoring the error handler afterwards using restore_error_handler

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)