Sometimes we have functions which aren’t intended to print (ie. output) anything. However, if some code within them throws an error, this will sometimes be output. That’ll mean that this error shows up in our final HTML at whatever point the function was run. To avoid this, it occurs to me that it might be a good idea to put ob_start();
at the start of the function, and ob_end();
at the end (or before the return
statement).
Is this a bad idea? Is it good practice? Are there pitfalls? Should I use ob_end_clean()
instead?
How nested output buffering works seems relevant, but I don’t understand this. It just occurs to me that my function might be called when another function has run ob_start();
but not yet run ob_end();
.
An example might be in WordPress or Drupal.
Advertisement
Answer
There are certainly pitfalls. As you stated yourself the whole thing breaks down once an unexpected exception is thrown and not caught. Same goes for fatal errors that may occur. Output buffering should only be used where you want to … well … buffer the output.
Whether or not an error is shown or not should be totally independent of that and you should properly set your error_reporting()
and display_errors
for that (i.e. don’t display anything on production environments).