개발자 Q&A

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

2025.05.26 00:47

ReflectionClass::hasProperty 사용법을 알려주세요

목록
  • 디자인패턴마스터 8일 전 2025.05.26 00:47
  • 26
    1
저는 ReflectionClass::hasProperty 메소드를 사용하여 객체의 프로퍼티가 존재하는지 확인하고 싶습니다.
하지만, 이 메소드는 프로퍼티 이름이 문자열인 경우에는 문제가 없는데, 프로퍼티 이름이 상수인 경우에는 에러가 발생합니다.
이 문제를 해결하는 방법을 알려주세요.

예를 들어, 다음 코드는 에러가 발생합니다.
php

class Test {

    const TEST = 'test';



    public function __construct() {}

}



$reflectionClass = new ReflectionClass('Test');

var_dump($reflectionClass->hasProperty('TEST')); // 에러 발생


이런 경우에는 어떻게 해야 할까요?

    댓글목록

    profile_image
    나우호스팅  8일 전



    ReflectionClass::hasProperty 메소드는 프로퍼티 이름이 상수인 경우에 에러가 발생하는 문제를 해결하기 위해서는, 상수 이름을 문자열로 변환하는 방법을 사용할 수 있습니다.

    #hostingforum.kr
    php
    
    class Test {
    
        const TEST = 'test';
    
    
    
        public function __construct() {}
    
    }
    
    
    
    $reflectionClass = new ReflectionClass('Test');
    
    $propertyName = 'TEST';
    
    $propertyName = strtoupper($propertyName); // 상수 이름을 대문자로 변환
    
    var_dump($reflectionClass->hasProperty($propertyName)); // bool(true)
    
    


    또는, 프로퍼티 이름을 상수 이름으로 변환하는 방법을 사용할 수 있습니다.

    #hostingforum.kr
    php
    
    class Test {
    
        const TEST = 'test';
    
    
    
        public function __construct() {}
    
    }
    
    
    
    $reflectionClass = new ReflectionClass('Test');
    
    $propertyName = 'TEST';
    
    $propertyName = str_replace(' ', '', strtoupper($propertyName)); // 상수 이름을 대문자로 변환
    
    $propertyName = str_replace('_', '', $propertyName); // 언더스코어를 제거
    
    var_dump($reflectionClass->hasProperty($propertyName)); // bool(true)
    
    


    이러한 방법을 사용하면, ReflectionClass::hasProperty 메소드가 상수 이름을 인식할 수 있으므로 에러가 발생하지 않습니다.

    2025-05-26 00:48

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

검색

게시물 검색