라이브러리
[PHP] ReflectionAttribute::newInstance - 이 ReflectionAttribute 클래스와 인수로 표현되는 속성 클래스를 인스턴스화합니다.
ReflectionAttribute::newInstance
PHP 8.1 버전부터 ReflectionAttribute 클래스가 추가되었습니다. 이 클래스는 PHP에서 사용할 수 있는 Attribute를 생성하고, 검사하는 데 사용됩니다. ReflectionAttribute::newInstance 메서드는 특정 Attribute를 인스턴스로 생성하는 데 사용됩니다.
# Attribute
Attribute는 PHP 8.1 버전부터 사용할 수 있는 기능입니다. Attribute는 클래스, 메서드, 프로퍼티에 추가할 수 있으며, 해당 클래스, 메서드, 프로퍼티의 특성을 나타냅니다. Attribute는 ReflectionAttribute 클래스를 사용하여 생성할 수 있습니다.
# ReflectionAttribute::newInstance
ReflectionAttribute::newInstance 메서드는 특정 Attribute를 인스턴스로 생성하는 데 사용됩니다. 이 메서드는 Attribute의 이름과 인수를 인수로 받습니다.
# 예제
다음 예제는 ReflectionAttribute::newInstance 메서드를 사용하여 Attribute를 생성하는 방법을 보여줍니다.
#hostingforum.kr
php
use Attribute;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
use ReflectionAttribute;
#[Attribute]
class MyAttribute {
public string $name;
public function __construct(string $name) {
$this->name = $name;
}
}
class MyClass {
#[MyAttribute(name: 'MyClass')]
public string $myProperty;
#[MyAttribute(name: 'MyClass')]
public function myMethod(): void {
// 메서드 구현
}
}
$reflectionClass = new ReflectionClass(MyClass::class);
$reflectionMethod = new ReflectionMethod(MyClass::class, 'myMethod');
$reflectionProperty = new ReflectionProperty(MyClass::class, 'myProperty');
$attribute = ReflectionAttribute::newInstance(MyAttribute::class, ['name' => 'MyClass']);
print($attribute->name . "
"); // 출력: MyClass
$attributes = $reflectionClass->getAttributes();
foreach ($attributes as $attribute) {
print($attribute->getName() . "
"); // 출력: MyAttribute
print($attribute->newInstance()->name . "
"); // 출력: MyClass
}
$attributes = $reflectionMethod->getAttributes();
foreach ($attributes as $attribute) {
print($attribute->getName() . "
"); // 출력: MyAttribute
print($attribute->newInstance()->name . "
"); // 출력: MyClass
}
$attributes = $reflectionProperty->getAttributes();
foreach ($attributes as $attribute) {
print($attribute->getName() . "
"); // 출력: MyAttribute
print($attribute->newInstance()->name . "
"); // 출력: MyClass
}
# 결과
이 예제를 실행하면, Attribute의 이름과 인수가 출력됩니다. Attribute의 이름은 `MyAttribute`이며, 인수는 `MyClass`입니다.
# 결론
ReflectionAttribute::newInstance 메서드는 특정 Attribute를 인스턴스로 생성하는 데 사용됩니다. 이 메서드는 Attribute의 이름과 인수를 인수로 받습니다. Attribute는 클래스, 메서드, 프로퍼티에 추가할 수 있으며, 해당 클래스, 메서드, 프로퍼티의 특성을 나타냅니다. Attribute는 ReflectionAttribute 클래스를 사용하여 생성할 수 있습니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.