라이브러리
[PHP] ReflectionParameter::getAttributes - 속성 가져오기
ReflectionParameter::getAttributes
`ReflectionParameter` 클래스는 PHP Reflection API의 일부로, 클래스나 함수의 파라미터에 대한 정보를 제공합니다. `getAttributes` 메소드는 파라미터에 적용된 애트리뷰트(Annotation) 정보를 반환합니다.
애트리뷰트(Annotation)란?
애트리뷰트는 클래스나 함수에 대한 추가 정보를 제공하는 메타데이터입니다. 애트리뷰트는 주로 클래스나 함수의 파라미터에 적용되어, 해당 파라미터의 의미나 사용 방법을 설명합니다.
예제
#hostingforum.kr
php
use Attribute;
use ReflectionClass;
use ReflectionParameter;
#[Attribute]
class MyAttribute {
public function __construct(public string $name) {}
}
class MyClass {
public function myMethod(MyAttribute $param1, MyAttribute $param2) {}
}
$reflectionClass = new ReflectionClass(MyClass::class);
$reflectionMethod = $reflectionClass->getMethod('myMethod');
$reflectionParams = $reflectionMethod->getParameters();
foreach ($reflectionParams as $param) {
$attributes = $param->getAttributes();
foreach ($attributes as $attribute) {
$name = $attribute->getName();
$name = $name === 'MyAttribute' ? $attribute->newInstance()->name : $name;
echo "파라미터 $name에 적용된 애트리뷰트: $name
";
}
}
위 예제에서는 `MyAttribute` 애트리뷰트를 적용한 `MyClass` 클래스의 `myMethod` 메소드의 파라미터에 대한 정보를 가져와, 각 파라미터에 적용된 애트리뷰트를 출력합니다.
결과
#hostingforum.kr
파라미터 name에 적용된 애트리뷰트: MyAttribute
파라미터 name에 적용된 애트리뷰트: MyAttribute
애트리뷰트 적용 방법
애트리뷰트를 적용하는 방법은 다음과 같습니다.
#hostingforum.kr
php
use Attribute;
#[Attribute]
class MyAttribute {
public function __construct(public string $name) {}
}
class MyClass {
#[MyAttribute(name: 'param1')]
public function myMethod($param1, $param2) {}
}
위 예제에서는 `MyAttribute` 애트리뷰트를 `myMethod` 메소드의 파라미터에 적용합니다.
애트리뷰트 정보 가져오기
`getAttributes` 메소드는 파라미터에 적용된 애트리뷰트 정보를 반환합니다. 각 애트리뷰트 정보는 `ReflectionAttribute` 객체로 반환됩니다.
#hostingforum.kr
php
use Attribute;
use ReflectionClass;
use ReflectionParameter;
use ReflectionAttribute;
#[Attribute]
class MyAttribute {
public function __construct(public string $name) {}
}
class MyClass {
public function myMethod(MyAttribute $param1, MyAttribute $param2) {}
}
$reflectionClass = new ReflectionClass(MyClass::class);
$reflectionMethod = $reflectionClass->getMethod('myMethod');
$reflectionParams = $reflectionMethod->getParameters();
foreach ($reflectionParams as $param) {
$attributes = $param->getAttributes();
foreach ($attributes as $attribute) {
$name = $attribute->getName();
$name = $name === 'MyAttribute' ? $attribute->newInstance()->name : $name;
echo "파라미터 $name에 적용된 애트리뷰트: $name
";
// 애트리뷰트 정보 가져오기
$reflectionAttribute = $attribute->getReflection();
echo "애트리뷰트 이름: " . $reflectionAttribute->getName() . "
";
echo "애트리뷰트 타입: " . get_class($reflectionAttribute) . "
";
}
}
위 예제에서는 `getAttributes` 메소드를 사용하여 파라미터에 적용된 애트리뷰트 정보를 가져와, 각 애트리뷰트의 이름, 타입을 출력합니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.