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.Even though PHP will close resources on termination for you doesn't mean that it's bad to explictly close them when you no longer need them .
In the average web page, the page is going to terminate shortly after, so letting PHP close them usually isn't terrible. However, what happens if for some reason the script is long-running? Then you have a resource leak. So why not just close everything when you no longer need it (or considering the scope of the destructor, when it's no longer available)?
Defining a destructor is as simiple as adding a __destruct()method to your class:
<?php
class MyCar{
function __construct(){
Print "Car is being assembly<br>";
}
function __destruct(){
print "Car is being disassembly";
}
}
$obj=new MyCar();
$obj=NULL;
?>
Output:
Car is being assembly
Car is being disassembly
Car is being disassembly
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 detroyed.Even without the last line,the destructor would be called,but it would be at the endof the request during the execution engine's shutdown.
No comments:
Post a Comment