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...
PHP - The __destruct FunctionA destructor is called when the object is destructed or the script is stopped or exited. If you create a __destruct() function, PHP will automatically call this function at the end of the script. Notice that the destruct function starts with two underscores (__)!
Example# __construct() is the most common magic method in PHP, because it is used to set up a class when it is initialized. The opposite of the __construct() method is the __destruct() method. This method is called when there are no more references to an object that you created or when you force its deletion.
Let's have a class:
class A {
public function __construct(){
echo "Construct\n";
}
public function __destruct(){
echo "Destruct\n";
}
}
And test code:
$test = new A();
die( "Dead\n"); // Will output Construct; dead; Destruct
$test = new A();
throw new Exception("Blah\n"); // 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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With