개발자 Q&A

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

2025.03.09 06:17

ReflectionProperty::hasType와 사용법에 대한 질문

목록
  • Go매니아 13일 전 2025.03.09 06:17
  • 6
    1
저는 ReflectionProperty::hasType을 사용하여 프로퍼티의 자료형을 확인하려고 합니다.
하지만, 다음의 코드에서 예상과 다른 결과가 나와서 고민이 됩니다.

php

$reflection = new ReflectionClass('MyClass');

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

echo $property->hasType(); // false



위의 코드를 실행하면 false가 출력됩니다.
하지만, $reflection->getProperty('myProperty')->getType()을 사용하면 ReflectionType는 반환됩니다.

php

$reflection = new ReflectionClass('MyClass');

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

echo $property->getType(); // ReflectionType



위의 코드를 실행하면 ReflectionType가 반환됩니다.
이러한 이유로, ReflectionProperty::hasType을 사용한 결과가 예상과 다르다는 것을 알게 되었습니다.
그럼 ReflectionProperty::hasType이 실제로 어떤 역할을 하는지 궁금합니다.

ReflectionProperty::hasType을 사용하여 프로퍼티의 자료형을 확인한 결과가 왜 false가 나올까요?

그리고, $reflection->getProperty('myProperty')->getType()을 사용하여 프로퍼티의 자료형을 확인한 결과가 ReflectionType가 나올까요?

    댓글목록

    profile_image
    나우호스팅  13일 전



    ReflectionProperty::hasType() 메서드는 프로퍼티가 타입 힌트를 가지고 있는지 여부를 확인하는 메서드입니다.

    타입 힌트는 PHP 7.0부터 지원되기 시작했습니다. 따라서, PHP 7.0 이전 버전의 코드에서 ReflectionProperty::hasType() 메서드를 사용하면 false가 반환됩니다.

    타입 힌트가 없거나 PHP 7.0 이전 버전의 코드에서 타입 힌트를 사용하지 않은 경우에도 false가 반환됩니다.

    반면, ReflectionProperty::getType() 메서드는 프로퍼티의 타입 힌트를 반환하는 메서드입니다. 이 메서드는 타입 힌트가 없거나 PHP 7.0 이전 버전의 코드에서 타입 힌트를 사용하지 않은 경우에도 ReflectionType 객체를 반환합니다.

    예를 들어, 다음 코드는 타입 힌트가 없는 프로퍼티를 생성합니다.

    #hostingforum.kr
    php
    
    class MyClass {
    
        public $myProperty;
    
    }
    
    


    이 경우, ReflectionProperty::hasType() 메서드는 false를 반환하지만, ReflectionProperty::getType() 메서드는 ReflectionType 객체를 반환합니다.

    #hostingforum.kr
    php
    
    $reflection = new ReflectionClass('MyClass');
    
    $property = $reflection->getProperty('myProperty');
    
    echo $property->hasType(); // false
    
    echo get_class($property->getType()); // ReflectionType
    
    


    타입 힌트를 사용하는 경우, ReflectionProperty::hasType() 메서드는 true를 반환하고, ReflectionProperty::getType() 메서드는 타입 힌트를 반환합니다.

    #hostingforum.kr
    php
    
    class MyClass {
    
        public int $myProperty;
    
    }
    
    


    이 경우, ReflectionProperty::hasType() 메서드는 true를 반환하고, ReflectionProperty::getType() 메서드는 ReflectionType 객체를 반환합니다.

    #hostingforum.kr
    php
    
    $reflection = new ReflectionClass('MyClass');
    
    $property = $reflection->getProperty('myProperty');
    
    echo $property->hasType(); // true
    
    echo get_class($property->getType()); // ReflectionType
    
    

    2025-03-09 06:18

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

검색

게시물 검색