牛牛在线工具

ReflectionParameter::getAttributes()

收录 8868 个 PHP 函数,含用途说明与用法示例。

ReflectionParameter::getAttributes()

获取参数的属性

函数:ReflectionParameter::getAttributes() 适用版本:PHP 8.0.0及以上 用法:ReflectionParameter::getAttributes()方法用于获取参数的属性。 参数:无 返回值:一个ReflectionAttribute对象的数组,每个对象表示参数的一个属性。 示例: class MyClass { public function myMethod(#[Attribute1] $param1, #[Attribute2('value')] $param2) { // ... } } $reflectionClass = new ReflectionClass('MyClass'); $reflectionMethod = $reflectionClass->getMethod('myMethod'); // 获取第一个参数的属性 $param1 = $reflectionMethod->getParameters()[0]; $attributes1 = $param1->getAttributes(); foreach ($attributes1 as $attribute) { $attributeName = $attribute->getName(); $attributeArguments = $attribute->getArguments(); echo "Attribute name: $attributeName\n"; echo "Attribute arguments: "; print_r($attributeArguments); } // 获取第二个参数的属性 $param2 = $reflectionMethod->getParameters()[1]; $attributes2 = $param2->getAttributes(); foreach ($attributes2 as $attribute) { $attributeName = $attribute->getName(); $attributeArguments = $attribute->getArguments(); echo "Attribute name: $attributeName\n"; echo "Attribute arguments: "; print_r($attributeArguments); } 输出: Attribute name: Attribute1 Attribute arguments: Array ( ) Attribute name: Attribute2 Attribute arguments: Array ( [0] => value ) 以上示例中,我们定义了一个类MyClass,其中有一个方法myMethod,该方法有两个带有属性的参数。我们使用ReflectionClass和ReflectionMethod来获取方法的反射,并使用getParameters()方法获取方法的参数反射。然后,我们使用getAttributes()方法获取每个参数的属性反射,并遍历输出每个属性的名称和参数。在这个示例中,第一个参数没有传递任何参数,而第二个参数传递了一个参数值为value的Attribute2属性。