我有这样的PHP代码:
<?php
class MyDestructableClass {
function __destruct() {
print "Destroying MyDestructableClass";
throw new Exception('Intentionally thrown exception, can it be caught?');
}
}
$obj = new MyDestructableClass();
exit; // Triggers destructor eventually
?>
当析构函数发生时(当exit()发生时抛出异常),我想打印一条特殊消息。我不能修改MyDestructableClass本身的内容,我只想注意它的析构函数何时抛出异常。
我尝试了一个异常处理程序:
<?php
class MyDestructableClass {
function __destruct() {
print "Destroying MyDestructableClass";
throw new Exception('Intentionally thrown exception, can it be caught?');
}
}
$obj = new MyDestructableClass();
function myExceptionHandler($exception)
{
print "I noticed an exception was thrown, success!";
}
set_exception_handler('myExceptionHandler');
exit; // Triggers destructor eventually
?>
但什么也没印出来。
我还尝试了一个关闭功能:
<?php
class MyDestructableClass {
function __destruct() {
print "Destroying MyDestructableClass";
throw new Exception('Intentionally thrown exception, can it be caught?');
}
}
$obj = new MyDestructableClass();
function myShutdownFunction()
{
if (error_get_last() != NULL) // Only want to react to errors, not normal shutdown
{
print "I noticed an exception was thrown, success!";
}
}
register_shutdown_function('myShutdownFunction');
exit; // Triggers destructor eventually
?>
但什么也没印出来。
什么技术可以注意到exit()启动的析构函数中的异常?
这对我有用。但我不知道这是否是你想要的。
<?php
class MyDestructableClass {
function __destruct() {
print "Destroying MyDestructableClass";
throw new Exception('Intentionally thrown exception, can it be caught?');
}
}
function RunEverything(){
$obj = new MyDestructableClass();
}
try {
RunEverything();
} catch (Exception $e){
echo 'My error has been thrown';
}
exit;
/*
*/
?