Recipe 7.3. Defining Object Destructors


7.3.1. Problem

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.

7.3.2. Solution

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

$car = new car; // buy new car ... unset($car);    // car wreck

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

class car {     function __destruct() {         // head to car dealer     } }

7.3.3. Discussion

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

// Destructor class Database {     function __destruct() {          db_close($this->handle); // close the database connection     } }

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.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

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