티스토리 뷰

배움/PHP

ReflectionClass ?

spaces25 2025. 7. 4. 12:52
반응형

✅ 기본 개념

ReflectionClass는 특정 클래스의 메서드, 속성, 상속 관계, 인터페이스, 주석(phpdoc) 등을 조사할 수 있습니다.

<?php
class User {
    public $name;
    private $password;

    public function login() {
        // ...
    }
}

// ReflectionClass 생성
$reflector = new ReflectionClass('User');

// 클래스 이름 출력
echo $reflector->getName(); // User

// public 속성 목록 출력
$properties = $reflector->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ($properties as $property) {
    echo $property->getName() . "\n";
}

// 메서드 목록 출력
$methods = $reflector->getMethods();
foreach ($methods as $method) {
    echo $method->getName() . "\n";
}

🔧 주요 메서드들

메서드 설명
getName() 클래스 이름 반환
getMethods() 메서드 목록 반환 (ReflectionMethod[])
getProperties() 속성 목록 반환 (ReflectionProperty[])
getConstants() 상수 목록 반환
getDocComment() 클래스에 대한 주석(phpdoc) 반환
isAbstract() 추상 클래스인지 여부
isInterface() 인터페이스인지 여부
isSubclassOf() 상속 관계 여부 확인
newInstance() 클래스의 인스턴스 생성 (생성자 호출 없이)
newInstanceArgs() 생성자 인자를 지정해 인스턴스 생성
hasMethod() 특정 메서드 존재 여부 확인
hasProperty() 특정 속성 존재 여부 확인
 

🧪 예시: 의존성 주입 도구처럼 사용하기

function createInstance($className) {
    $reflection = new ReflectionClass($className);
    if (!$reflection->isInstantiable()) {
        throw new Exception("Cannot instantiate $className");
    }

    $constructor = $reflection->getConstructor();
    if (!$constructor) {
        return new $className();
    }

    $params = $constructor->getParameters();
    $dependencies = [];

    foreach ($params as $param) {
        $type = $param->getType();
        if ($type && !$type->isBuiltin()) {
            $dependencies[] = createInstance($type->getName());
        } else {
            throw new Exception("Cannot resolve parameter: " . $param->getName());
        }
    }

    return $reflection->newInstanceArgs($dependencies);
}

이런 방식은 DI 컨테이너(예: Laravel의 서비스 컨테이너)에서도 사용됩니다.


🧩 사용 사례

  • 의존성 주입 및 서비스 컨테이너
  • PHPUnit 테스트 프레임워크
  • 동적 클래스 분석 도구
  • 자동 라우팅/등록 시스템
  • API 문서 생성기
반응형

'배움 > PHP' 카테고리의 다른 글

call_user_func  (0) 2025.07.14
array_combine 함?  (1) 2025.07.11
ob_get_contents  (0) 2025.07.03
Http 파사드(Illuminate\Support\Facades\Http)  (0) 2025.07.02
Laravel Helper Class 사용법  (0) 2025.07.01
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함