關於此函數有兩個重要的點沒有被記錄下來
1) 追蹤不包括拋出例外所在的檔案/行號;該條目僅記錄在最上層的 getFile/Line 方法中。
2) 元素以「最接近優先」的順序傳回,例如,如果您有一個腳本 x 呼叫函數 y,而函數 y 又呼叫函數 z 拋出例外,那麼第一個追蹤元素將是 'Y',而第二個將是 'X'。
(PHP 5,PHP 7,PHP 8)
Exception::getTrace — 取得堆疊追蹤
此函數沒有任何參數。
以 array 形式傳回 Exception 堆疊追蹤。
範例 #1 Exception::getTrace() 範例
<?php
function test() {
throw new Exception;
}
try {
test();
} catch(Exception $e) {
var_dump($e->getTrace());
}
?>
上述範例會輸出類似以下的內容
array(1) { [0]=> array(4) { ["file"]=> string(22) "/home/bjori/tmp/ex.php" ["line"]=> int(7) ["function"]=> string(4) "test" ["args"]=> array(0) { } } }
關於此函數有兩個重要的點沒有被記錄下來
1) 追蹤不包括拋出例外所在的檔案/行號;該條目僅記錄在最上層的 getFile/Line 方法中。
2) 元素以「最接近優先」的順序傳回,例如,如果您有一個腳本 x 呼叫函數 y,而函數 y 又呼叫函數 z 拋出例外,那麼第一個追蹤元素將是 'Y',而第二個將是 'X'。
如果您想在 PHP 7.4 上查看堆疊追蹤中的參數,請注意在 php.ini 檔案中現在有一個 zend 旗標,其預設設定為 Off。
zend.exception_ignore_args = Off
將此旗標設定為 On,它將再次顯示參數。
zend.exception_ignore_args = On
https://php.dev.org.tw/manual/en/ini.core.php#ini.zend.exception-ignore-args
在呼叫 getTrace() 時,傳回的陣列中也有類別的名稱
<?php
class Test {
function __construct() {
throw new Exception('FATAL ERROR: bla bla...');
}
}
try {
$obj = new Test();
} catch(Exception $e) {
var_dump($e->getTrace());
}
?>
將顯示類似以下的內容
array(1) {
[0]=> array(6) {
["file"]=> string(54) "/....../test.php"
["line"]=> int(37)
["function"]=> string(11) "__construct"
["class"]=> string(4) "Test"
["type"]=> string(2) "->"
["args"]=> array(0) { }
}
}
您可以使用此函數格式化例外
<?php
function MakePrettyException(Exception $e) {
$trace = $e->getTrace();
$result = 'Exception: "';
$result .= $e->getMessage();
$result .= '" @ ';
if($trace[0]['class'] != '') {
$result .= $trace[0]['class'];
$result .= '->';
}
$result .= $trace[0]['function'];
$result .= '();<br />';
return $result;
}
//範例:
try {
$obj = new Test();
} catch(Exception $e) {
echo MakePrettyException($e);
}
?>
結果
Exception: "FATAL ERROR: bla bla..." @ Test->__construct();
追蹤的順序從例外的來源開始,不包括 main。
例如
<?php
function Bar() {
throw new Exception;
}
function Foo() {
Bar();
}
try {
Foo();
} catch(Exception $e) {
var_dump($e->getTrace());
}
?>
將輸出
array(2) {
[0]=>
array(4) {
["file"]=>
string(21) "/.../test.php"
["line"]=>
int(8)
["function"]=>
string(3) "Bar"
["args"]=>
array(0) {
}
}
[1]=>
array(4) {
["file"]=>
string(21) "/.../test.php"
["line"]=>
int(12)
["function"]=>
string(3) "Foo"
["args"]=>
array(0) {
}
}
}
從 PHP 7.4 開始,Exception::getTrace()(和 Error::getTrace())的傳回值不再包含像 debug_backtrace() 帶有預設選項的 "args" 鍵。
因此,自 7.4 以來的傳回值類似於 debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS)。