You want to define a method that is called when an object is destroyed. For example, you want to automatically save information from a database into an object when it's deleted.
Objects are automatically destroyed when a script terminates. To force the destruction of an object, use unset( ), as shown in Example 7-6.
Deleting an object
To make PHP call a method when an object is eliminated, define a method named __destruct( ), as shown in Example 7-7.
Defining an object destructor
It's not normally necessary to manually clean up objects, but if you have a large loop, unset( ) can help keep memory usage from spiraling out of control.
PHP 5 supports object destructors. Destructors are like constructors, except that they're called when the object is deleted. Even if you don't delete the object yourself using unset( ), PHP still calls the destructor when it determines that the object is no longer used. This may be when the script ends, but it can be much earlier.
You use a destructor to clean up after an object. For instance, the Database destructor would disconnect from the database and free up the connection. Unlike constructors, you cannot pass information to a destructor, because you're never sure when it's going to be run.
Therefore, if your destructor needs any instance-specific information, store it as a property, as shown in Example 7-8.
Accessing instance-specific data within a destructor
Destructors are executed before PHP terminates the request and finishes sending data. Therefore, you can print from them, write to a database, or even ping a remote server.
You cannot, however, assume that PHP will destroy objects in any particular order. Therefore, you should not reference another object in your destructor, as PHP may have already destroyed it. Doing so will not cause a crash, but it will cause your code to behave in an unpredictable (and buggy) manner.
There are no backward compatibility issues with destructors, because they aren't available in PHP 4. However, that doesn't mean people didn't try to recreate them using other language features. If you emulated destructors, you will want to port your code, because PHP 5's destructors are more efficient and easier to use.
7.3.4. See Also
Documentation on unset( ) at http://www.php.net/unset.