라이브러리

[PHP] ReflectionProperty::isReadOnly - 속성이 읽기 전용인지 확인합니다.




ReflectionProperty::isReadOnly


PHP의 ReflectionProperty 클래스는 PHP의 클래스, 인터페이스, 함수, 상수 및 속성에 대한 정보를 제공합니다. ReflectionProperty::isReadOnly 메서드는 특정 속성이 읽기 전용인지 여부를 확인하는 데 사용됩니다.

사용법


ReflectionProperty::isReadOnly 메서드는 속성이 읽기 전용인지 여부를 boolean 값으로 반환합니다. 속성이 읽기 전용이면 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 Doe', 30);



$reflectionClass = new ReflectionClass('Person');

$reflectionProperty = $reflectionClass->getProperty('name');



echo $reflectionProperty->isReadOnly() ? 'true' : 'false'; // true



$reflectionProperty = $reflectionClass->getProperty('age');

echo $reflectionProperty->isReadOnly() ? 'true' : 'false'; // true



$reflectionProperty = $reflectionClass->getProperty('name');

$reflectionProperty->setAccessible(true);

$reflectionProperty->setValue($person, 'Jane Doe');

echo $person->getName(); // Jane Doe



$reflectionProperty = $reflectionClass->getProperty('age');

$reflectionProperty->setAccessible(true);

try {

    $reflectionProperty->setValue($person, 31);

} catch (Exception $e) {

    echo 'age 속성은 읽기 전용입니다.' . PHP_EOL;

}



결과


#hostingforum.kr


true

true

Jane Doe

age 속성은 읽기 전용입니다.



결론


ReflectionProperty::isReadOnly 메서드는 속성이 읽기 전용인지 여부를 확인하는 데 사용됩니다. 속성이 읽기 전용이면 true를 반환하고, 그렇지 않으면 false를 반환합니다. 이 메서드는 속성을 읽기 전용으로 만들거나, 속성을 읽기 전용으로 만들지 않았는지 확인하는 데 사용할 수 있습니다.
  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 10,077건 / 276 페이지

검색

게시물 검색