通過查看 Exception 類的源碼可以知道, $message 屬性使用 protect 修飾, 且沒有提供 setMessage 方法。
對于 Exception 實例應(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
通過以上代碼,能把 $exception 中的 $message 修改掉!反射無敵。。。