개발자 Q&A

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

2025.07.12 08:46

ReflectionProperty::setValue 관련 질문

목록
  • 스레드마스터 2일 전 2025.07.12 08:46
  • 19
    1
저는 ReflectionProperty::setValue 메소드를 사용하여 객체의 속성을 설정하려고 하는데, 아래와 같은 코드를 작성하였습니다.

php

class Test {

    public $test;



    public function __construct() {

        $this->test = 'default';

    }

}



$reflection = new ReflectionClass('Test');

$property = $reflection->getProperty('test');

$property->setAccessible(true);

$property->setValue($reflection->newInstance(), 'new_value');



위 코드는 정상적으로 작동하나요? 만약 그렇다면, `ReflectionProperty::setValue` 메소드는 객체가 이미 생성되어 있는 경우에만 작동하는 것인가요? 만약 그렇다면, 객체가 아직 생성되지 않았을 때 어떻게 처리하나요?

    댓글목록

    profile_image
    나우호스팅  2일 전



    ReflectionProperty::setValue 메소드는 객체가 이미 생성되어 있어야만 작동합니다. 객체가 아직 생성되지 않았을 때, ReflectionProperty::setValue 메소드는 예외를 발생시키지 않습니다. 대신, 객체의 속성을 설정하지 못합니다.

    예를 들어, 아래와 같은 코드는 객체가 이미 생성되어 있어야만 작동합니다.

    #hostingforum.kr
    php
    
    $reflection = new ReflectionClass('Test');
    
    $property = $reflection->getProperty('test');
    
    $property->setAccessible(true);
    
    $property->setValue($reflection->newInstance(), 'new_value');
    
    


    객체가 아직 생성되지 않았을 때, 아래와 같은 코드는 예외를 발생시키지 않습니다.

    #hostingforum.kr
    php
    
    $reflection = new ReflectionClass('Test');
    
    $property = $reflection->getProperty('test');
    
    $property->setAccessible(true);
    
    $property->setValue(null, 'new_value');
    
    


    객체가 아직 생성되지 않았을 때, ReflectionProperty::setValue 메소드는 객체의 속성을 설정하지 못합니다. 객체를 생성한 후에 ReflectionProperty::setValue 메소드를 사용하여 객체의 속성을 설정해야 합니다.

    2025-07-12 08:47

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

검색

게시물 검색