9.7 Creating a Class Destructor


You want to create a destructor for your current class.

Technique

Use PHP's register_shutdown_function() function and register a function that frees your object:

 <?php $CLASSNAME_OBJECT_LIST = array(); function classname_destructor () {     global $CLASSNAME_OBJECT_LIST;     if (count($CLASSNAME_OBJECT_LIST)) {         reset($CLASSNAME_OBJECT_LIST);         while (list(, $obj) = each($CLASSNAME_OBJECT_LIST)) {             $obj->destroy();         }         $CLASSNAME_OBJECT_LIST = null;     } } class Tree {     var $type;     function Tree ($type='oak') {         $this->type = $type;         global $CLASSNAME_OBJECT_LIST;         array_push ($CLASSNAME_OBJECT_LIST, &$this);     }     function destroy () {         $this->type = null;     } } register_shutdown_function("classname_destructor"); ?> 

Description

In the preceding example, we register a shutdown function with the register_ shutdown_function() function. This function will be called when your script is finished executing. Then this function calls the destructor method ( destroy() in this case, but it could be any other method that you choose) on every object in the global $CLASSNAME_OBJECT_LIST variable. An object is added to the object list in the class's constructor by adding a reference to the special $this variable to the array.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net