When will __destruct not be called in PHP?

user198729 picture user198729 · Mar 5, 2010 · Viewed 29.5k times · Source
class MyDestructableClass {
   function __construct() {
       print "\nIn constructor\n";
       $this->name = "MyDestructableClass";
   }

   function __destruct() {
       print "\nDestroying " . $this->name . "\n";
   }
}

$obj = new MyDestructableClass();

When the above script is in a complex environment,the __destruct won't get called when exit,but I can't reproduce it easily.Have someone ever noticed this ?

EDIT

I'll post the whole stuff here,it's the testing environment of symfony,which means you can easily reproduce it if you are familar with the framework:

require_once dirname(__FILE__).'/../bootstrap/Doctrine.php';


$profiler = new Doctrine_Connection_Profiler();

$conn = Doctrine_Manager::connection();
$conn->setListener($profiler);

$t = new lime_test(0, new lime_output_color());

class MyDestructableClass {
   function __construct() {
       print "\nIn constructor\n";
       $this->name = "MyDestructableClass";
   }

   function __destruct() {
       print "\nDestroying " . $this->name . "\n";
   }
}

$obj = new MyDestructableClass();
$news = new News();

$news->setUrl('http://test');
$news->setHash('http://test');
$news->setTitle('http://test');
$news->setSummarize('http://test');
$news->setAccountId(1);
$news->setCategoryId(1);
$news->setThumbnail('http://test');
$news->setCreatedAt(date('Y-m-d H:i:s',time()));
$news->setUpdatedAt(date('Y-m-d H:i:s',time()));
$news->save();
exit();

Answer

edorian picture edorian · Mar 5, 2010

The __destruct will not be called:

  • If exit is called in another destructor
  • Depending on the PHP Version: if exit is called in a shutdown function registered with register_shutdown_function
  • If there is a fatal error somewhere in the code
  • If another destructor throws an exception
  • If you try to handle an exception in a destructor (PHP >= 5.3.0)

Guess that's all I can think of right now

& What Pascal MARTIN said. That's the first step of debugging that.