
ReflectionProperty::setAccessible 메소드를 사용할 때 예외를 처리하는 방법은 다음과 같습니다.
1. `$obj`가 `null`일 때: 이 경우, ReflectionProperty::setAccessible 메소드는 예외를 발생시키지 않습니다. 하지만, `$obj`가 `null`일 때, `$reflectionProperty->getValue($obj)` 메소드는 ReflectionException을 발생시킵니다. 따라서, `$obj`가 `null`일 때는 `$reflectionProperty->getValue($obj)` 메소드 호출 전에 `$obj`를 확인하는 것이 좋습니다.
2. `$obj`가 객체가 아닌 경우: 이 경우, ReflectionProperty::setAccessible 메소드는 예외를 발생시키지 않습니다. 하지만, `$reflectionProperty->getValue($obj)` 메소드는 ReflectionException을 발생시킵니다. 따라서, `$obj`가 객체가 아닌 경우에는 `$reflectionProperty->getValue($obj)` 메소드 호출 전에 `$obj`를 확인하는 것이 좋습니다.
예외를 처리하는 방법은 다음과 같습니다.
#hostingforum.kr
php
try {
$reflectionProperty = new ReflectionProperty($obj, 'propertyName');
$reflectionProperty->setAccessible(true);
$propertyValue = $reflectionProperty->getValue($obj);
} catch (ReflectionException $e) {
// 예외 처리 코드
}
또한, `$obj`가 `null`이나 객체가 아닌 경우를 확인하는 코드를 추가하여 예외를 처리할 수 있습니다.
#hostingforum.kr
php
if ($obj === null) {
// 예외 처리 코드
} elseif (!is_object($obj)) {
// 예외 처리 코드
} else {
$reflectionProperty = new ReflectionProperty($obj, 'propertyName');
$reflectionProperty->setAccessible(true);
$propertyValue = $reflectionProperty->getValue($obj);
}
2025-03-11 16:19