您的位置:首页 > 技术中心 > PHP教程 >

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

时间:2022-02-11 12:49

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

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

以上就是php通过反射修改Exception实例的message属性的详细内容,更多请关注gxlsystem其它相关文章!

本类排行

今日推荐

热门手游