개발자 Q&A

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

2025.05.18 01:08

ReflectionParameter::export에 대한 질문

목록
  • 데이터베이스귀신 2시간 전 2025.05.18 01:08 새글
  • 2
    1
제가 ReflectionParameter::export를 사용하여 클래스의 속성을 출력하려고 하는데, 어떤 방법이 가장 좋을까요?

제가 지금까지는 다음과 같이 코드를 작성했는데, 어떤 부분이 잘못된 것인지 알려주세요.

php

class User {

    public $name;

    public $age;



    public function __construct($name, $age) {

        $this->name = $name;

        $this->age = $age;

    }

}



$reflection = new ReflectionClass('User');

$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);



foreach ($properties as $property) {

    $export = $property->export();

    echo $export . "n";

}



이 코드는 어떤 문제가 있는 것인지 알려주세요.

    댓글목록

    profile_image
    나우호스팅  2시간 전



    ReflectionParameter::export를 사용하여 클래스의 속성을 출력할 때, 문제가 있는 코드는 다음과 같습니다.

    - ReflectionParameter::export는 ReflectionParameter 객체를 반환합니다. 하지만, ReflectionClass::getProperties는 ReflectionProperty 객체를 반환합니다. 따라서, $property->export()는 오류가 발생합니다.

    - ReflectionClass::getProperties는 클래스의 모든 속성을 반환합니다. 하지만, ReflectionProperty::IS_PUBLIC을 사용하여 공개 속성만 반환하고 싶다면, ReflectionClass::getProperties(ReflectionProperty::IS_PUBLIC) 대신 ReflectionClass::getProperties()를 사용하는 것이 좋습니다.

    - export() 메서드는 PHP 7.4에서 deprecated되었으며, PHP 8.0부터는 삭제되었습니다. 대신, ReflectionProperty::getName() 메서드를 사용하여 속성 이름을 출력하는 것이 좋습니다.

    - export() 메서드는 속성 이름과 타입을 함께 출력합니다. 하지만, 타입 정보는 ReflectionProperty::getType() 메서드를 사용하여 별도로 얻을 수 있습니다.

    - export() 메서드는 속성의 초기화 값을 함께 출력합니다. 하지만, 초기화 값을 얻으려면 ReflectionProperty::getValue() 메서드를 사용해야 합니다.

    따라서, 다음과 같이 코드를 수정할 수 있습니다.

    #hostingforum.kr
    php
    
    class User {
    
        public $name;
    
        public $age;
    
    
    
        public function __construct($name, $age) {
    
            $this->name = $name;
    
            $this->age = $age;
    
        }
    
    }
    
    
    
    $reflection = new ReflectionClass('User');
    
    $properties = $reflection->getProperties();
    
    
    
    foreach ($properties as $property) {
    
        $name = $property->getName();
    
        $type = $property->getType();
    
        $value = $property->getValue();
    
    
    
        echo "속성 이름: $namen";
    
        echo "속성 타입: " . ($type ? $type->getName() : '없음') . "n";
    
        echo "속성 초기화 값: $valuenn";
    
    }
    
    


    이 코드는 속성 이름, 타입, 초기화 값을 모두 출력합니다.

    2025-05-18 01:09

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

검색

게시물 검색