php - Are there pitfalls to using output buffering in functions that shouldn't have output?
Get the solution ↓↓↓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 putob_start();
at the start of the function, andob_end();
at the end (or before thereturn
statement).
Is this a bad idea? Is it good practice? Are there pitfalls? Should I useob_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 runob_start();
but not yet runob_end();
.
An example might be in WordPress or Drupal.
Answer
Solution:
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 and
for that (i.e. don't display anything on production environments).
Answer
Solution:
it seems that you need to use exception. It allows doing what you want if your code does some unexpected happened.
In the example below, you can see how it could work
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Exceptions See the documentation for more
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to a member function format() on string
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.