
ReflectionClass::getProperties 함수는 private 속성을 반환하지 않습니다. 하지만 private 속성을 반환하고 싶다면, private 속성을 public 속성으로 변경하거나, getter/setter 메소드를 사용하여 접근할 수 있습니다.
private 속성을 public 속성으로 변경하는 방법은 다음과 같습니다.
#hostingforum.kr
php
class Test {
private $privateProperty;
public function __construct() {
$this->privateProperty = 'private value';
}
public function getPrivateProperty() {
return $this->privateProperty;
}
}
$reflection = new ReflectionClass('Test');
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PRIVATE);
foreach ($properties as $property) {
$property->setAccessible(true);
echo $property->getName() . ': ' . $property->getValue(new Test()) . "n";
}
getter/setter 메소드를 사용하는 방법은 다음과 같습니다.
#hostingforum.kr
php
class Test {
private $privateProperty;
public function __construct() {
$this->privateProperty = 'private value';
}
public function getPrivateProperty() {
return $this->privateProperty;
}
public function setPrivateProperty($value) {
$this->privateProperty = $value;
}
}
$reflection = new ReflectionClass('Test');
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PRIVATE);
foreach ($properties as $property) {
$property->setAccessible(true);
if ($property->getName() == 'privateProperty') {
echo $property->getName() . ': ' . $property->getValue(new Test()) . "n";
$property->setValue(new Test(), 'new value');
echo $property->getName() . ': ' . $property->getValue(new Test()) . "n";
}
}
property_info 변수의 값을 변경할 수 있는 방법은 다음과 같습니다.
#hostingforum.kr
php
class Test {
private $privateProperty;
public function __construct() {
$this->privateProperty = 'private value';
}
public function getPrivateProperty() {
return $this->privateProperty;
}
}
$reflection = new ReflectionClass('Test');
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PRIVATE);
foreach ($properties as $property) {
$property->setAccessible(true);
if ($property->getName() == 'privateProperty') {
echo $property->getName() . ': ' . $property->getValue(new Test()) . "n";
$property->setAccessible(false);
$property->setAccessible(true);
echo $property->getName() . ': ' . $property->getValue(new Test()) . "n";
}
}
위의 예제에서 property_info 변수의 값을 변경할 수 있는 방법은 ReflectionProperty::setAccessible() 메소드를 사용하여 접근할 수 있습니다.
2025-06-26 21:13