PHP4, Constructors, $this and Output Buffering

Just spent half an hour trying to figure out a very random bug in a PHP4 application I'm developing at the moment. I'm using an MVC design pattern and in the constructor for the View object I wanted the class to set itself up to capture all output using output buffering. I've used this style in a couple of sites now and once it was all figured out, it worked fine but this time I was doing one subtle thing differently.

This time around I was using the following code:

PHP:
  1. class viewXHTML
  2. {
  3.         function viewXHTML($model)
  4.         {
  5.             if ($model === null)
  6.                 return;
  7.  
  8.             $this->model = $model;
  9.  
  10.             ob_start(array(&$this, 'output'));
  11.         }
  12.  
  13.         function output($text)
  14.         {
  15.             []
  16.         }
  17. []

Which sets the model to an instance variable and provides the output buffering function a callback to the output function of this object. This works fine and dandy, when the page is done, the output function gets called with the parameter being all output that was sent using echo and print statements. The problem is only visible when you want to access instance variables of your object within that function.

Theory One:

The output function was being called on a copy of the original object. Problem was that some of the instance variables were set but the ones set after the constructor weren't. Turns out that the $this variable you get given in the constructor is a special object which you can't pass by reference, only by value.

This was all fixed by calling a bind method after the constructor returned so the code is now similar to:

PHP:
  1. class viewXHTML
  2. {
  3.         function viewXHTML($model)
  4.         {
  5.             if ($model === null)
  6.                 return;
  7.  
  8.             $this->model = $model;
  9.         }
  10.  
  11.         function bindOutput()
  12.         {
  13.             ob_start(array(&$this, 'output'));
  14.         }
  15.  
  16.         function output($text)
  17.         {
  18.             []
  19.         }
  20. []

The bindOutput function is now called straight after the constructor in my bootstrap code.

Anyway, this mildly reiterates to me that I really shouldn't be pushing PHP4 to do things that I should be using Ruby, maybe Python or at very least PHP5 to do.

This was in PHP v4.4.1.

edit: typos for the win
edit2: added syntax highlight plugin


No Responses to “PHP4, Constructors, $this and Output Buffering”

Leave a Reply

Comments will be sent to the moderation queue.

Note: This post is over 3 years old. You may want to check later in this blog to see if there is new information relevant to your comment.