PHP modifies the message attribute of Exception instance through reflection

藏色散人
Release: 2023-04-08 07:04:01
forward
3368 people have browsed it

PHP modifies the message attribute of Exception instance through reflection

By looking at the source code of the Exception class, we can know that the $message attribute is decorated with protect and does not provide a setMessage method.

How should I modify the message for Exception instances? The answer is: reflection!

$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
Copy after login

With the above code, the $message in $exception can be modified! Invincible reflection. . .

For more PHP related knowledge, please visit PHP Tutorial!

The above is the detailed content of PHP modifies the message attribute of Exception instance through reflection. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:lukachen.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template