views:

92

answers:

1

Hello,

im trying to understand php constructor and destructor behaviour. Everything goes as expected with the constructor but i am having trouble getting the destructor to fire implicitly. Ive done all the reading on php.net and related sites, but i cant find an answer to this question.

If i have a simple class, something like:

class test{

     public funciton __construct(){
          print "contructing<br>";
     }

     public function __destruct(){
          print "destroying<br>";
     }
}

and i call it with something like:

$t = new test;

it prints the constructor message. However, i'd expect that when the scripts ends and the page is rendered that the destructor should fire. Of course it doesnt.

If i call unset($t); when the scripts ends, of course the destructor fires, but is there a way to get it to fire implicitly?

thanks for any tips

+1  A: 

The __destruct() magic function is executed when the object is deleted/destroyed (using unset). It is not called during shutdown of a script. When a php script finishes executing, it cleans up the memory, but it doesn't 'delete' objects as such, thus the __destruct() methods aren't called.

You may be thinking of the register_shutdown_function(), which is fired when your php script finishes executing.

function shutdown()
{
    // code here
    echo 'this will be called last';
}

register_shutdown_function('shutdown');
Ben Rowe
alright, thanks for the explanation
kris
Actually, according to the manual this isn't true. See http://php.net/manual/en/language.oop5.decon.php. "The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence."
Arda Xi