개발자 Q&A

개발하다 막혔다면? 여기서 질문하세요! 초보부터 고수까지, 함께 고민하고 해결하는 공간입니다. 누구나 자유롭게 질문하고 답변을 남겨보세요!

2025.03.24 23:39

ReflectionProperty::getValue 사용 방법에 대한 질문

목록
  • 펜테스터마법사 1일 전 2025.03.24 23:39
  • 2
    1
안녕하세요 선생님.
ReflectionProperty::getValue 메소드를 사용하여 객체의 속성을 가져올 때,
속성이 private 속성일 경우에는 어떻게 값을 가져올 수 있을까요?
예를 들어, private $name; 속성이 있다고 가정할 때,
getValue 메소드를 사용하여 name 속성의 값을 가져올 수 있는 방법을 알려주세요.

    댓글목록

    profile_image
    나우호스팅  1일 전



    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

  • 개발자 Q&A 포인트 정책
      글쓰기
      50P
      댓글
      10P
  • 전체 6,408건 / 16 페이지

검색

게시물 검색