라이브러리
[PHP] ReflectionProperty::getValue - 값을 가져옵니다.
ReflectionProperty::getValue
PHP의 ReflectionProperty 클래스는 PHP 클래스의 속성을 반영하는 데 사용됩니다. ReflectionProperty::getValue 메소드는 지정된 클래스의 속성의 현재 값을 반환합니다.
# 사용법
ReflectionProperty::getValue 메소드는 다음 형식으로 사용됩니다.
#hostingforum.kr
php
ReflectionProperty::getValue($object, $name)
* `$object` : 속성을 가져올 클래스의 인스턴스입니다.
* `$name` : 속성의 이름입니다.
# 예제
다음 예제는 ReflectionProperty::getValue 메소드를 사용하여 클래스의 속성을 가져오는 방법을 보여줍니다.
#hostingforum.kr
php
class Person {
public $name;
public $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
}
$person = new Person('John Doe', 30);
$reflectionClass = new ReflectionClass('Person');
$reflectionProperty = $reflectionClass->getProperty('name');
$reflectionProperty->setAccessible(true);
echo ReflectionProperty::getValue($person, 'name'); // John Doe
echo "
";
echo $reflectionProperty->getValue($person); // John Doe
위 예제에서, `ReflectionProperty::getValue` 메소드는 `Person` 클래스의 `name` 속성을 가져옵니다. 또한 `setAccessible(true)` 메소드를 사용하여 속성을 접근할 수 있도록 합니다.
# 참고
* `ReflectionProperty` 클래스는 PHP 5.0.0 이상에서 사용할 수 있습니다.
* `setAccessible(true)` 메소드는 속성을 접근할 수 있도록 합니다. 하지만, 속성을 수정할 수는 없습니다. 속성을 수정하려면 `setValue` 메소드를 사용해야 합니다.
* `ReflectionProperty` 클래스는 클래스의 속성을 반영하는 데 사용됩니다. 하지만, 속성을 생성하거나 삭제하는 데 사용할 수는 없습니다.
추가 예제
다음 예제는 `ReflectionProperty` 클래스를 사용하여 클래스의 속성을 확인하는 방법을 보여줍니다.
#hostingforum.kr
php
class Person {
public $name;
public $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
}
$person = new Person('John Doe', 30);
$reflectionClass = new ReflectionClass('Person');
$reflectionProperties = $reflectionClass->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ($reflectionProperties as $reflectionProperty) {
$reflectionProperty->setAccessible(true);
echo $reflectionProperty->getName() . ': ' . ReflectionProperty::getValue($person, $reflectionProperty->getName()) . "
";
}
위 예제에서, `ReflectionClass` 클래스의 `getProperties` 메소드를 사용하여 클래스의 속성을 가져옵니다. 그리고 `foreach` 문을 사용하여 속성을 반복적으로 확인합니다. 속성을 확인할 때, `setAccessible(true)` 메소드를 사용하여 속성을 접근할 수 있도록 합니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.