PHP:如何在异常处理程序中获取所有定义的变量

PHP:如何在异常处理程序中获取所有定义的变量,php,exception,Php,Exception,我正在编写一个异常日志脚本,我使用set_exception_handler()来处理未捕获的异常 在我的自定义异常处理程序中,我使用get_defined_vars(),但它只返回一个带有异常对象的数组,在抛出异常之前创建的所有变量都消失了 $testing_var = 'testtesttest'; try { throw new Exception("Error Processing Request"); } catch (Exception $e) { var_dump(get_def

我正在编写一个异常日志脚本,我使用set_exception_handler()来处理未捕获的异常

在我的自定义异常处理程序中,我使用get_defined_vars(),但它只返回一个带有异常对象的数组,在抛出异常之前创建的所有变量都消失了

$testing_var = 'testtesttest';

try {
throw new Exception("Error Processing Request");
} catch (Exception $e) {
var_dump(get_defined_vars()); // this could get $testing_var 
}

set_exception_handler('exception_handler');

function exception_handler(exception)
{
 var_dump(get_defined_vars()); // no, it can't get $testing_var, exception object only
}

throw new Exception("Error Processing Request");

在调用
get_defined_vars()
的作用域中,没有定义所要查找的变量,因此当然不会返回该变量:

此函数返回一个多维数组,其中包含所有已定义变量的列表,这些变量可以是环境变量、服务器变量或用户定义变量,在调用get_defined_vars()的范围内

你想达到什么目标?通常,在构造异常时,应该将处理异常所需的所有信息传递给异常。可能使用自定义异常类:

<?php

// custom exception class
// could be extended with constructor accepting an optional context
class ContextAwareException extends Exception
{
    private $context;

    public function setContext($context)
    {
        $this->context = $context;
    }

    public function getContext()
    {
        return $this->context;
    }
}

function exception_handler($exception)
{
    if ($exception instanceof ContextAwareException) {
        $exception->getContext();
    } else {
        // we have no context
    }
}

/*
 * using this exception
 */

$testing_var = 'testtesttest';

$exception = new ContextAwareException("Error Processing Request");
$exception->setContext(get_defined_vars());
throw $exception;

我找到了另一种方法。我也在寻找异常解决方案,但这一个适合我。如果您使用错误而不是异常,那么它似乎是有效的

set_error_handler('test','handler');

class test {

    public static function handler($code, $error, $file = NULL, $line = NULL) {

        throw new Exception($error, $code, 0, $file, $line);

        return true;
    }
}

$testVar='carolines';

try { 
    trigger_error('megamsg');
}

catch(Exception $e) {

    var_dump($e);

    $vars=$E BLABLABLA

}

找到如何从$e中提取。但是如果您进行调试,您将在跟踪处理程序函数调用中看到$testVar变量

,我认为使用xdebug和
collect_参数
collect_变量
conf选项是可能的。您是对的,我无法从处理程序的作用域中获取$testing_var。不幸的是,处理程序是针对未捕获异常的,这意味着异常是由系统引发的,类型是不可预测的,但我仍然需要这些变量,还有其他方法可以实现吗?确实是针对未捕获异常的,但这并不意味着它们是由系统引发的,这意味着它们没有被捕获。。。您可以抛出自定义异常而不捕获它。如果您希望使用这种方法处理第三方代码引发的异常,我认为您运气不好。仅供参考,我认为您正在寻找错误问题的解决方案。也许您应该详细说明为什么需要异常范围的变量,这似乎是设计上的缺陷。