__destruct有多可靠?
Are there situations in which this method would not be called?
I'm thinking to store a important variable into a persistent cache just before the cache object gets destroyed. This variable is used many times in the page so I wouldn't like to update the cache with it every time the variable changes...
是否存在不会调用此方法的情况? p>
I 我想在缓存对象被销毁之前将一个重要变量存储到持久缓存中。 这个变量在页面中多次使用,所以每次变量改变时我都不想用它来更新缓存...... p> div>
Let's have a class:
class A {
public function __construct(){
echo "Construct
";
}
public function __destruct(){
echo "Destruct
";
}
}
And test code:
$test = new A();
die( "Dead
"); // Will output Construct; dead; Destruct
$test = new A();
throw new Exception("Blah
"); // Construct, Fatal error (no destruct)
$test = new A();
require_once( 'invalid_file.php'); // Construct, Fatal error (no destruct)
So basically: there are situations (fatal errors) when destructor won't be called.
Ah and this question has the same answer as this one: When will __destruct not be called in PHP? (+/-)
It seems there at least was a problem using Windows: https://github.com/WoltLab/WCF/blob/ff7e6ed381f2ccab7f51220f97087921133b2237/wcfsetup/install/files/lib/system/WCF.class.php#L122
I don't know whether this is still relevant.
It is called as soon as there are no more references to that particular object, or during the shutdown sequence. The manual also states destructors are called when scripts are terminated with exit().
Aside from the issue pointed out by TimWolla, I am not aware of any problems with PHP destructors.