How do I stop PHP output buffering from eating error messages?

后端 未结 2 717
旧巷少年郎
旧巷少年郎 2021-01-13 02:55

Well, now that I\'ve gotten a bit further into it, I realize that this is a stupid question, and wrong. Turns out that the author of the legacy code I maintain was hi-jackin

2条回答
  •  旧时难觅i
    2021-01-13 03:29

    Exceptions penetrate ob_start() shield

    If you want to stop PHP script execution, rather throw an Exception, which will penetrate the ob_start(), ob_end_flush() shield

    echo 'before output buffer';
    ob_start();
    throw new Exception('this will be seen');
    ob_end_flush();
    

    Consider creating a Logger class

    Don't output directly with your method, rather use a class or a holder which incorporates the log (or error method in your case), eg:

    class Logger
    {
        private $_messages = array();
    
        public function __construct()
        {
            $this->_messages['errors'] = array();
            $this->_messages['debug'] = array();
        }
    
        public function error($msg)
        {
            $this->_messages['errors'][] = $msg;
        }
    
        public function debug($msg)
        {
            $this->_messages['debug'] = $msg;
        }
    
        public function getErrors()
        {
            return $this->_messages['errors'];
        }
    
    }
    
    $logger = new Logger();
    
    $logger->error('error1');
    
    ob_start();
    
    $logger->error('error2');
    
    ob_end_flush();
    
    print_r($logger->getErrors());
    

    this way you can rely on the holder object, it will not discard messages and get all errors, that you wanted to display

提交回复
热议问题