Consider the following script:
<?php ob_start(); print "Hello first!\n"; ob_start(); print "Hello second!\n"; ob_clean(); ?>
As you can see ob_start() is called a second time without ending the first buffer - what do you think the script will output?
If you guessed "Hello first" without any sign of "Hello second", pat yourself on the back - the first buffer is started and filled with "Hello first". A second buffer is then started on top of the previous buffer, leaving the original still intact just out of reach for the time being, and then the new buffer is filled with "Hello second". Finally, ob_clean() is called, clearing the most recent buffer (but leaving others untouched)
Stacking your output buffers might not seem like much help at first, but remember that it is generally smart to make your whole page buffered in a master buffer, which means without stackable buffers you would be unable to use any other buffers inside the main page. It is thanks to stackable buffers you can open a buffer at the beginning of each page, then open and use new buffers throughout the script as needed.
Want to learn PHP 7?
Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Flushing stacked buffers >>
Previous chapter: Reusing buffers
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.