.
3ss.cn

php经过反射修改Exception实例的message属性

通过查看 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 修改掉!反射无敌。。。

赞(0)
未经允许不得转载:互联学术 » php经过反射修改Exception实例的message属性

评论 抢沙发