PHP Conference Japan 2024

Exception::__toString

(PHP 5, PHP 7, PHP 8)

Exception::__toString例外的字串表示

說明

public Exception::__toString(): string

返回例外的 字串 表示。

參數

此函式沒有參數。

回傳值

返回例外的 字串 表示。

範例

範例 #1 Exception::__toString() 範例

<?php
try {
throw new
Exception("一些錯誤訊息");
} catch(
Exception $e) {
echo
$e;
}
?>

上述範例將輸出類似以下的內容

exception 'Exception' with message 'Some error message' in /home/bjori/tmp/ex.php:3
Stack trace:
#0 {main}

參見

新增註釋

使用者貢獻的註釋 1 則註釋

devnull
4 個月前
Exception __toString 的實作也會包含鏈結到此例外的前一個例外的字串表示,位置在目前例外的字串表示_之前_。

例如

<?php
class OuterException extends Exception {}
class
MiddleException extends Exception {}
class
InnerException extends Exception {}

$excA = new InnerException("inner exception", 0);
$excB = new MiddleException("middle exception", 0, $excA);
$excC = new OuterException("outer exception", 0, $excB);

echo
"The exception is:\n$excC";
?>

將會印出以下內容

例外為
InnerException: inner exception in test.php:6
堆疊追蹤
#0 {main}

Next MiddleException: middle exception in test.php:7
堆疊追蹤
#0 {main}

Next OuterException: outer exception in test.php:8
堆疊追蹤
#0 {main}
To Top