exception.png

通过查看 Exception 类的源码可以知道, $message 属性使用 protect 修饰, 且没有提供 setMessage 方法。
对于 Exception 实例应该怎么修改 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 修改掉!反射无敌。。。