PHP Gotcha #437

May 19th, 2008 by patrick

PHP has some handy functions to handle operations that you want to have happen at the end of page processing.  Most people are aware of using destructors (__destruct) in object oriented code.  These are handy for saving data and closing references to external resources on script exit.  This mechanism is available in PHP5 but not in PHP4.  So then how do you handle those types of operations in PHP4?

PHP also has a global function, register_shutdown_function, that takes a callback argument.  This callback gets loaded onto a stack and called once the script is about to finish processing.  You could use this in a similar fashion to ensure that all the housekeeping tasks are taken care of at the end of a script.  But, here’s the gotcha.  

PHP5 not only changed the way that objects work but also where they stand in the grand lifecycle of a PHP script.  Even if you’re using PHP4 style objects on the PHP5 interpreter, object destructors are called AFTER the functions in the shutdown stack, meaning that you can pass class methods to the shutdown stack and they will be executed normally.  In the PHP4 interpreter, objects are deallocated before the shutdown functions are called.  Meaning that if you have references to any PHP object in them, that function will not be called (nor as I found out, will you get an error informing you of such).  Why are people still using PHP4 again?

UPDATE:

This actually has to do with registering the shutdown function in the object’s constructor, and the state at which it was pushed onto the stack.  Evidently herein lies the difference between the interpreters.

Posted in software

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.