Programming Tutorials

Destructors in PHP

By: Andi, Stig and Derick in PHP Tutorials on 2008-11-22  

Destructor functions are the opposite of constructors. They are called when the object is being destroyed (for example, when there are no more references to the object). As PHP makes sure all resources are freed at the end of each request, the importance of destructors is limited. However, they can still be useful for performing certain actions, such as flushing a resource or logging information on object destruction. There are two situations where your destructor might be called: during your script's execution when all references to an object are destroyed, or when the end of the script is reached and PHP ends the request. The latter situation is delicate because you are relying on some objects that might already have had their destructors called and are not accessible anymore. So, use it with care, and don't rely on other objects in your destructors.

Defining a destructor is as simple as adding a __destruct() method to your class:

class MyClass {
function __destruct()
{
print "An object of type MyClass is being destroyed\n";
}
}
$obj = new MyClass();
$obj = NULL;

This script prints An object of type MyClass is being destroyed In this example, when $obj = NULL; is reached, the only handle to the object is destroyed, and therefore the destructor is called, and the object itself is destroyed. Even without the last line, the destructor would be called, but it would be at the end of the request during the execution engine's shutdown.

Tip: The exact point in time of the destructor being called is not guaranteed by PHP, and it might be a few statements after the last reference to the object has been released. Thus, be aware not to write your application in a way where this could hurt you.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

PHP code to write to a CSV file from MySQL query

Different versions of PHP - History and evolution of PHP

PHP code to import from CSV file to MySQL

Send push notifications using Expo tokens in PHP

Encrypting files using GnuPG (GPG) via PHP

A Basic Example using PHP in AWS (Amazon Web Services)

PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......

Parent: child process exited with status 3221225477 -- Restarting

Decrypting files using GnuPG (GPG) via PHP

Error: Length parameter must be greater than 0

Convert a hex string into a 32-bit IEEE 754 float number in PHP

Password must include both numeric and alphabetic characters - Magento

Convert XML to CSV in PHP

PHP file upload prompts authentication for anonymous users

Reading word by word from a file in PHP

Latest Articles (in PHP)