L-Train L-Train - 2 years ago 65
PHP Question

start output buffering in one class method and end it in another class method

I have been programming in php for many, many years and have used output buffering in several of my classes and class methods. Recently, while writing a template class, my mind began to roam. The following is where my mind went :

This is just an example.

class someClass {
protected $contents;

public function __construct() {
// execute some code here.

private function someMethod() {
// execute some code here.
$this->contents = ob_get_contents();

public function someOtherMethod() {
echo $this->contents;

Consider the example code above.


  • Can output buffering be used like this?

  • The use of output buffering prevents code from being written before headers are sent, but what, if any, other benefits would come from this?

  • If this is possible, is it practical?

Answer Source

Debugging is the biggest benefit, especially when responding to ajax requests ( ie. must return valid json even on errors, when you have no control over the other endpoint ) so you cache all out put and if a shutdown is hit ( -via- register_shutdown_function() ) you format the output as json - with the appropriate error and trace data ect. that's the biggest use i have for it. You'll have issues with nested ob_start though. Even then it's a bit debatable if that is really useful or not. It can also be good to dump the output to text files, for error reporting, but that is beside using it in a method, and is more dependent on your projects needs.

I do very sensitive work that needs to obscure 99% of error outputting and log it to text, and just show generic errors to end user;

this might save you some headaches

     * dump all levels of ob_start into message
     * @return string
    public static function obGetCleanNested(){
        $message = '';
        for($i=0; $i < ob_get_level(); $i++){
            $message .= ob_get_clean();
        return $message;    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download