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 )

Latest Articles (in PHP)