개발자 Q&A

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

2025.03.23 02:56

ReflectionMethod::getDeclaringClass 예외 처리 방법

목록
  • ReactNative장인 1일 전 2025.03.23 02:56
  • 2
    1
제가 ReflectionMethod::getDeclaringClass를 사용하여 클래스를 가져오려고 하는데,
반환된 클래스가 null 인 경우 어떻게 처리해야 하나요?

예를 들어, 다음과 같은 코드가 있다고 가정해 보겠습니다.

php

$reflectionMethod = new ReflectionMethod('MyClass', 'myMethod');

$declaringClass = $reflectionMethod->getDeclaringClass();

if ($declaringClass !== null) {

    echo $declaringClass->getName();

} else {

    echo "클래스가 존재하지 않습니다.";

}



만약 MyClass의 myMethod가 존재하지 않는 경우, $declaringClass는 null이 됩니다.
이 경우 어떻게 처리해야 하나요?

    댓글목록

    profile_image
    나우호스팅  1일 전



    ReflectionMethod::getDeclaringClass를 사용하여 클래스를 가져올 때, 반환된 클래스가 null인 경우에는 다음과 같이 처리할 수 있습니다.

    1. null 체크를 하여 클래스가 존재하지 않는 경우를 별도로 처리합니다.
    2. try-catch 블록을 사용하여 예외를 처리합니다. ReflectionMethod::getDeclaringClass가 null을 반환하는 경우에는 Exception이 발생하지 않습니다.
    3. ReflectionMethod::getDeclaringClass가 null을 반환하는 경우, 클래스가 존재하지 않는다는 의미이므로, 별도의 처리를 할 수 있습니다.

    다음은 예시입니다.

    #hostingforum.kr
    php
    
    $reflectionMethod = new ReflectionMethod('MyClass', 'myMethod');
    
    $declaringClass = $reflectionMethod->getDeclaringClass();
    
    
    
    if ($declaringClass !== null) {
    
        echo $declaringClass->getName();
    
    } else {
    
        echo "클래스가 존재하지 않습니다.";
    
    }
    
    


    위 코드는 MyClass의 myMethod가 존재하지 않는 경우, 클래스가 존재하지 않는다는 메시지를 출력합니다.

    또한, try-catch 블록을 사용하여 예외를 처리할 수도 있습니다.

    #hostingforum.kr
    php
    
    try {
    
        $reflectionMethod = new ReflectionMethod('MyClass', 'myMethod');
    
        $declaringClass = $reflectionMethod->getDeclaringClass();
    
        echo $declaringClass->getName();
    
    } catch (Exception $e) {
    
        echo "클래스가 존재하지 않습니다.";
    
    }
    
    


    위 코드는 MyClass의 myMethod가 존재하지 않는 경우, 클래스가 존재하지 않는다는 메시지를 출력합니다.

    2025-03-23 02:57

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

검색

게시물 검색