
ReflectionProperty::getValue 메소드를 사용하여 private 속성의 값을 가져올 때, 객체의 인스턴스를 생성하고, ReflectionClass를 통해 ReflectionProperty를 얻어내어 getValue 메소드를 호출할 수 있습니다.
예시:
#hostingforum.kr
php
class Person {
private $name;
public function __construct($name) {
$this->name = $name;
}
}
$person = new Person('John');
$reflectionClass = new ReflectionClass('Person');
$reflectionProperty = $reflectionClass->getProperty('name');
$reflectionProperty->setAccessible(true);
echo $reflectionProperty->getValue($person); // John
위 예시에서, ReflectionProperty::setAccessible(true) 메소드를 호출하여 private 속성에 접근할 수 있습니다.
또한, PHP 7.4 이상 버전부터는 ReflectionProperty::setAccessible(true) 메소드를 호출하지 않고도 private 속성에 접근할 수 있습니다.
예시:
#hostingforum.kr
php
class Person {
private $name;
public function __construct($name) {
$this->name = $name;
}
}
$person = new Person('John');
$reflectionClass = new ReflectionClass('Person');
$reflectionProperty = $reflectionClass->getProperty('name');
echo $reflectionProperty->getValue($person); // John
위 예시에서, ReflectionProperty::getValue 메소드를 호출하여 private 속성의 값을 가져올 수 있습니다.
2025-03-24 23:40