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

php通过反射修改Exception实例的message属性,第1张

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

更多PHP相关知识,请访问PHP教程!

以上就是php通过反射修改Exception实例的message属性的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/679550.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-20
下一篇 2022-04-20

发表评论

登录后才能评论

评论列表(0条)

保存