라이브러리
[PHP] ReflectionClass::isReadOnly - 클래스가 읽기 전용인지 확인합니다.
PHP ReflectionClass::isReadOnly 메서드는 클래스의 속성이 읽기 전용인지 여부를 확인하는 데 사용됩니다. 읽기 전용 속성은 속성을 수정하거나 삭제할 수 없으며, 속성을 읽을 수만 있습니다.
ReflectionClass::isReadOnly 사용법
ReflectionClass::isReadOnly 메서드는 ReflectionProperty 객체를 반환합니다. 이 객체는 클래스의 속성을 나타냅니다. 메서드는 다음을 반환합니다.
- `true` : 속성이 읽기 전용입니다.
- `false` : 속성이 읽기 전용이 아닙니다.
예제
#hostingforum.kr
php
class Person {
private $name;
private $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function getName() {
return $this->name;
}
public function getAge() {
return $this->age;
}
}
$person = new Person('John', 30);
$reflectionClass = new ReflectionClass('Person');
$reflectionProperty = $reflectionClass->getProperty('name');
echo var_export($reflectionProperty->isReadOnly(), true) . "
"; // false
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($person, 'Jane');
echo $person->getName() . "
"; // Jane
위 예제에서 `Person` 클래스의 `name` 속성은 읽기 전용이 아닙니다. `isReadOnly()` 메서드는 `false`를 반환합니다. `setAccessible(true)` 메서드를 사용하여 속성을 읽기 전용으로 설정하지 않은 상태에서 속성을 수정할 수 있습니다.
읽기 전용 속성 만들기
읽기 전용 속성을 만들려면 속성을 `private` 또는 `protected`으로 선언하고 getter 메서드를 만들면 됩니다.
#hostingforum.kr
php
class Person {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
$person = new Person('John');
$reflectionClass = new ReflectionClass('Person');
$reflectionProperty = $reflectionClass->getProperty('name');
echo var_export($reflectionProperty->isReadOnly(), true) . "
"; // true
위 예제에서 `Person` 클래스의 `name` 속성은 읽기 전용입니다. `isReadOnly()` 메서드는 `true`를 반환합니다.
결론
PHP ReflectionClass::isReadOnly 메서드는 클래스의 속성이 읽기 전용인지 여부를 확인하는 데 사용됩니다. 읽기 전용 속성은 속성을 수정하거나 삭제할 수 없으며, 속성을 읽을 수만 있습니다. 읽기 전용 속성을 만들려면 속성을 `private` 또는 `protected`으로 선언하고 getter 메서드를 만들면 됩니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.