如何通过PHP反射机制更改Exception对象的message属性值?
- 内容介绍
- 文章标签
- 相关推荐
本文共计274个文字,预计阅读时间需要2分钟。
通过查看`Exception`类的源码,可以知道`$message`属性使用`protected`修饰,因此不能直接访问。没有提供`setMessage`方法,所以不能直接修改`message`。
对于`Exception`实例,要修改`message`属性,可以通过反射来实现。以下是修改`message`的示例代码:
php!$exception=new Exception('haha');$reflection=new ReflectionObject($exception);$reflectionProperty=$reflection->getProperty('message');$reflectionProperty->setAccessible(true);$reflectionProperty->setValue($exception, 'new 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属性的详细内容,更多请关注自由互联其它相关文章!
本文共计274个文字,预计阅读时间需要2分钟。
通过查看`Exception`类的源码,可以知道`$message`属性使用`protected`修饰,因此不能直接访问。没有提供`setMessage`方法,所以不能直接修改`message`。
对于`Exception`实例,要修改`message`属性,可以通过反射来实现。以下是修改`message`的示例代码:
php!$exception=new Exception('haha');$reflection=new ReflectionObject($exception);$reflectionProperty=$reflection->getProperty('message');$reflectionProperty->setAccessible(true);$reflectionProperty->setValue($exception, 'new 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属性的详细内容,更多请关注自由互联其它相关文章!

