Reusing Buffers

The functions ob_end_flush() and ob_end_clean() are complemented by ob_flush() and ob_clean(), which do the same jobs but don't end the output buffer. We could rewrite the previous script like this:

    ob_start();
    print "Hello First!\n";
    ob_flush();
    print "Hello Second!\n";
    ob_clean();
    print "Hello Third!\n";

This time the buffer is flushed but left open, then cleaned and still left open, and finally, automatically closed and flushed by PHP as the script ends. This saves creating and destroying output buffers, which is about 60% faster than opening and closing buffers all the time.

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.