我有这样的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()启动的析构函数中的异常?
答案 0 :(得分:0)
这对我有用。但我不知道这是不是你想要的。
<?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;
/*
*/
?