在PHP中,是否有可能知道您是否已经处于异常中?


Is it possible to know if you're already in an exception in PHP?

我在__destruct()方法中有一些代码有时会抛出异常。__destruct()方法在另一个异常期间被调用,我看到一个模糊的错误:

PHP Fatal error:  Ignoring exception from exampleClass::__destruct() while an exception is already active

隐藏了被调用的实际异常。我想这样做:

public function __destruct() 
{
  try
  {
    // do work here
  }
  catch(Exception $e)
  {
    // check if we're already in an exception and log it
    if(already_in_exception())
    {
      error_log($e->getMessage());
    }
    // normal destruct, re-throw
    else
    {
      throw $e;
    }
  } 
}

如果它是PHP 5.1.6兼容加分!

提前感谢!

你的问题不是因为你从另一个内部抛出了一个异常,而是因为你从析构函数抛出了一个异常。

From php.net: http://php.net/manual/en/language.oop5.decon.php

"注意:试图从析构函数抛出异常(在脚本终止时调用)会导致致命错误。"

重新考虑你的逻辑习惯,在解构之前做这个。