Stacking buffers

Consider the following script:

    print "Hello first!\n";

    print "Hello second!\n";


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.


Next chapter: Flushing stacked buffers >>

Previous chapter: Reusing buffers

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.