Search code examples
phpvariableslocal-variablesoutput-buffering

Output buffering vs. storing content into variable in PHP


I don't know exactly how output buffering works but as far as know it stores content into some internal variable.

Regarding this, what is the difference of not using output buffering and storing content in my own local variable instead and than echo it at the end of script?

Example with output buffering:

<?php
  ob_start();
  echo "html page goes here";
  ob_end_flush();
?>

And example without using output buffering:

<?php
  $html = "html page goes here";
  echo $html;
?>

What is the difference?


Solution

  • The main differences:

    1.) you can use "normal" output syntax, so for example an echo statement. You don't have to rewrite your problem.

    2.) you have better control about the buffering, since buffers can be stacked. You don't have to know about naming conventions and the like, this makes implementations easier where the writing and using side are implemented separate from each other.

    3.) no additional logic require to output buffered content, you just flush. Especially interesting if the output stream is something special. Why burden the controlling scope with dealing with that?

    4.) you can use the same output implementation regardless of an output buffer has been created. THis is a question of transparency.

    5.) you can 'catch' accidentially out bubbled stuff like warnings and the like and simply swallow it afterwards.

    [...]