Reputation: 1954
Is it possible to prevent the destructor to be executed when an exception is thrown?
Basically, my constructor is currently set to save some information to a file. However, this happends even when I've thrown an error when I would assume php would halt and stop all together.
Example:
<?php
class Test {
function __construct() {
echo "constructor";
}
function __destruct() {
echo "destructor";
}
function Hello() {
echo "Hello World";
}
}
$foo = new Test;
$foo->Hello();
throw new Exception("Error Processing Request", 1);
// output: constructorHelloWorlddestructor
// expected output: constructorHelloWorld
?>
Upvotes: 0
Views: 1163
Reputation: 3237
The php manual says:
The destructor will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing.
It therefore appears it is not possible to prevent the destructor from being called.
Reference: https://www.php.net/manual/en/language.oop5.decon.php#language.oop5.decon.destructor
Upvotes: 1
Reputation: 126
No it's not possible.
You could do a bunch of hack like registering a excetion handler and assigning a static variable to flag that you are in a error flow and check that variable in the destructor before executing the code. But since you cannot be sure of when the destructor will be call you are not sure if it's after the exception but before the variable assigment.
But overall you are probably not using the destructor for what it's use for, and to be honest I have been developing for 15 years and I count on my one hand how many time I have use a destructor there is normally others more efficient design pattern... More context will be needed.
Upvotes: 2