用Exception获取 函数/方法 调用过程

通常我们在某些拿不准的地方会抛出一个异常来表示,调用者可以输出该异常来追踪错误来源。

其实也可以使用Exception的实例来获取调用过程,这在分析一个函数/方法的调用情况比较方便

class A {
    public static function hello() {
        b();
    }
}

function b() {
    a();
}

function a() {
    $e = new Exception("hello");
    //echo "file: " . $e->getFile() . PHP_EOL;
    //echo "line: " . $e->getLine() . PHP_EOL;
    //echo "message: " . $e->getMessage() . PHP_EOL;
    //echo "trace: " . $e->getTrace() . PHP_EOL;
    //echo "traceString: " . $e->getTraceAsString() . PHP_EOL;

    var_dump($e->getTrace());
}

A::hello();

 

将会获得

array(3) {
  [0]=>
  array(4) {
    ["file"]=>
    string(40) "A.php"
    ["line"]=>
    int(11)
    ["function"]=>
    string(1) "a"
    ["args"]=>
    array(0) {
    }
  }
  [1]=>
  array(4) {
    ["file"]=>
    string(40) "A.php"
    ["line"]=>
    int(6)
    ["function"]=>
    string(1) "b"
    ["args"]=>
    array(0) {
    }
  }
  [2]=>
  array(6) {
    ["file"]=>
    string(40) "A.php"
    ["line"]=>
    int(25)
    ["function"]=>
    string(5) "hello"
    ["class"]=>
    string(1) "A"
    ["type"]=>
    string(2) "::"
    ["args"]=>
    array(0) {
    }
  }
}

 

 

posted on 2014-03-03 16:57  mtima  阅读(571)  评论(0编辑  收藏  举报

导航