Home >Backend Development >PHP Tutorial >PHP modifies the message attribute of Exception instance through reflection

PHP modifies the message attribute of Exception instance through reflection

藏色散人
藏色散人forward
2019-12-31 17:19:143397browse

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

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!

Statement:
This article is reproduced at:lukachen.com. If there is any infringement, please contact admin@php.cn delete