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:
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
outputfunction 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$thisvariable 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:
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
Alex Taylor is a web developer living and working in
January 15th, 2007 at 9:42 pm
Huzzar for finding the bug.
Mmmmmm ruby? I really should have a look into it.