通過(guò)查看 Exception 類的源碼可以知道, $message 屬性使用 protect 修飾, 且沒(méi)有提供 setMessage 方法。
對(duì)于 Exception 實(shí)例應(yīng)該怎么修改 message 呢?答案是: 反射!
$exception = new Exception('haha'); $message = " - use reflection appended message"; $reflectionObject = new ReflectionObject($exception); $reflectionObjectProp = $reflectionObject->getProperty('message'); $reflectionObjectProp->setAccessible(true); $reflectionObjectProp->setValue($exception, $exception->getMessage() . $message); print_r($exception->getMessage()); haha - use reflection appended message
通過(guò)以上代碼,能把 $exception 中的 $message 修改掉!反射無(wú)敵。。。