通过查看 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属性的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号