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
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!