php의 ReflectionClass에 대해 알아보자
ReflectionClass는 PHP에서 기본으로 제공하는 클래스입니다. 이 클래스는 리플렉션(Reflection) API의 일부로, 객체 지향 프로그래밍에서 클래스의 메타 데이터를 조사하는 데 사용됩니다.
ReflectionClass를 사용하면 다음과 같은 작업을 수행할 수 있습니다:
- 클래스 이름, 네임스페이스, 상속 관계 등의 기본 정보 조회
- 클래스에 정의된 메서드, 프로퍼티, 상수 등의 멤버들에 대한 정보 조회
- 클래스의 주석 (DocComment) 가져오기
- 클래스의 생성자에 대한 정보 얻기
- 그 밖에 클래스와 관련된 많은 메타 데이터에 접근 가능
이러한 리플렉션 기능은 동적으로 클래스를 분석하거나 프레임워크, 라이브러리 등에서 객체를 자동으로 생성하고 조작할 때 유용하게 사용됩니다.
<?php
class SampleClass {
private $property1 = "Private Property";
public $property2 = "Public Property";
public function sampleMethod() {
return "This is a sample method.";
}
}
// ReflectionClass 객체를 생성
$reflectedClass = new ReflectionClass('SampleClass');
// 클래스 이름 출력
echo "Class Name: " . $reflectedClass->getName() . "\n";
// 클래스의 메서드들을 가져와서 출력
echo "\nMethods:\n";
foreach ($reflectedClass->getMethods() as $method) {
echo "- " . $method->name . "\n";
}
// 클래스의 프로퍼티들을 가져와서 출력
echo "\nProperties:\n";
foreach ($reflectedClass->getProperties() as $property) {
echo "- " . $property->name . "\n";
}
// 클래스의 특정 프로퍼티의 접근 제어자를 확인
$property = $reflectedClass->getProperty('property1');
echo "\nIs 'property1' private? " . ($property->isPrivate() ? "Yes" : "No") . "\n";