函数名称:ReflectionAttribute::newInstance()
适用版本:PHP 8.0.0 及以上
用法:ReflectionAttribute::newInstance() 函数用于创建一个新的 ReflectionAttribute 对象,并传递参数作为构造函数的参数。
语法:public static ReflectionAttribute::newInstance(mixed $class, string $name, mixed ...$args): ReflectionAttribute|false
参数:
- $class:要创建属性的类名或对象。
- $name:要创建的属性的名称。
- $args:构造函数的参数。
返回值:
- 成功时返回 ReflectionAttribute 对象。
- 失败时返回 false。
示例:
#[Attribute]
class MyAttribute {
public function __construct($param1, $param2) {
// 构造函数逻辑
}
}
class MyClass {
#[MyAttribute('value1', 'value2')]
public function myMethod() {
// 方法逻辑
}
}
$reflection = new ReflectionClass('MyClass');
$attributes = $reflection->getMethod('myMethod')->getAttributes('MyAttribute');
foreach ($attributes as $attribute) {
$newInstance = ReflectionAttribute::newInstance($attribute->getName(), $attribute->getArguments());
var_dump($newInstance);
}
上述示例中,我们定义了一个名为 MyAttribute 的自定义属性类。然后,在 MyClass 类中使用了该属性。通过 ReflectionClass、ReflectionMethod 和 ReflectionAttribute 类,我们可以获取到 MyClass 类中 myMethod 方法上的 MyAttribute 属性,并使用 ReflectionAttribute::newInstance() 创建一个新的 ReflectionAttribute 对象。
请注意,示例中的 #[Attribute] 是 PHP 8.0 引入的属性语法糖,用于定义一个自定义属性类。在 PHP 8.0 之前的版本中,可以使用 PHP 自带的 Attribute 类来实现类似的功能。