리플렉션

리플렉션 (Reflection)

클래스나 함수가 어떤 모습인지 — 속성, 메서드, 매개변수, 주석까지 — 코드 자체를 런타임에 들여다보고 싶을 때가 있어요. PHP는 그런 기능을 위한 완전한 리플렉션 API를 내장하고 있습니다.

출처: PHP 공식 매뉴얼 - Reflection

본문

PHP는 완전한 리플렉션 API를 제공해요. 이를 통해 클래스·인터페이스·함수·메서드·확장을 내부(introspect) 로 들여다볼 수 있습니다. 추가로 함수·클래스·메서드에 대한 문서 주석(doc comment) 을 가져오는 방법도 제공합니다.

Note — 내부 API 중 일부는 Reflection 확장과 함께 쓰기 위한 코드가 빠져 있을 수 있어요. 예를 들어 내부 PHP 클래스가 프로퍼티에 대한 리플렉션 데이터가 없을 수도 있습니다. 이런 경우는 대부분 버그로 간주되므로 발견돼서 수정되어야 해요.

리플렉션 클래스 계층

핵심 리플렉션 클래스로는 다음이 있어요.

  • Reflection — 공통 유틸리티. export, getModifierNames
  • ReflectionClass — 클래스 리플렉션
  • ReflectionClassConstant — 클래스 상수 리플렉션
  • ReflectionConstant — 상수 리플렉션
  • ReflectionEnum, ReflectionEnumUnitCase, ReflectionEnumBackedCase — enum 관련
  • ReflectionMethod — 메서드 리플렉션
  • ReflectionFunction, ReflectionFunctionAbstract — 함수 리플렉션
  • ReflectionParameter — 함수/메서드 매개변수 리플렉션
  • ReflectionProperty — 프로퍼티 리플렉션
  • ReflectionExtension — 확장 리플렉션
  • ReflectionGenerator, ReflectionFiber — 제너레이터·파이버 관련
  • ReflectionZendExtension — Zend 확장 리플렉션
  • ReflectionAttribute — 속성(attribute) 리플렉션
  • ReflectionObject — 객체에서 직접 만드는 리플렉션
  • ReflectionReference — 참조 리플렉션
  • ReflectionNamedType, ReflectionUnionType, ReflectionIntersectionType — 타입 리플렉션

각 클래스는 get* 형태의 조회 메서드와 is* 형태의 판별 메서드를 두루 갖추고 있어요. 예를 들어 ReflectionClass는 다음과 같은 메서드를 제공합니다.

  • 조회: getName, getShortName, getNamespaceName, getParentClass, getInterfaces, getTraitNames, getMethods, getProperties, getConstants, getConstructor, getDocComment, getFileName, getStartLine, getEndLine, getExtensionName, getAttributes
  • 판별: isAbstract, isFinal, isInterface, isTrait, isEnum, isInternal, isUserDefined, isInstance, isInstantiable, isCloneable, isSubclassOf, inNamespace
  • 동작: newInstance, newInstanceArgs, newInstanceWithoutConstructor, newInstanceWithoutConstructor, newLazyGhost, newLazyProxy, setStaticPropertyValue, getStaticPropertyValue, hasMethod, hasProperty, hasConstant

enum 관련으로 ReflectionEnumgetBackingType, getCase, getCases, hasCase, isBacked 같은 메서드를, ReflectionClassConstantgetType, hasType, isDeprecated, isEnumCase, isFinal, isPrivate/isProtected/isPublic/isReadOnly 등을 제공합니다.

예제·확장

  • Examples: 리플렉션 사용 예제
  • Extending: Reflection을 상속·확장하는 법

리플렉션은 자동 문서화, 의존성 주입(DI), 디버깅 도구, 데코레이터 등 프레임워크 계열 코드에서 광범위하게 쓰여요.

더 알아보기