PHP Output Buffering - Callback Functions
(Page 3 of 5 )
Arguably the most powerful element of output buffering is the capability of defining callback functions. You can define a function to be called when the buffer is flushed to the screen. This callback function receives the buffer as a parameter. The returned value is then printed.
<?php // Start buffering with a callback function ob_start("callback"); print "Line 1\n"; print "Line 2\n";
// Flush the contents ob_flush(); print "Line 3\n";
// Define the callback function function callback($buffer) { return "Here's the buffer: $buffer"; } ?> |
The script displays lines 1 through 3. After printing line 2, the buffer is flushed. This passes the data to the callback function, which prepends to trite little message. Since the buffer isn't closed before the end of the script, PHP automatically flushes the buffer, which calls the callback function once again. One of the examples below deals with callback functions more in depth.
There are a couple of things to remember when using callback functions. You have to return what you want to displayed, not print it. The print command doesn't work in the callback function. Also, you cannot use output buffering inside of a callback function. It's because of some United Nations resolution or something. It just can't be done, so don't try it.
Next: Examples >>
More Miscellaneous Articles
More By Codewalkers