ReflectionParameter::getAttributes
PHP function
Edit on GitHub ✎
(PHP 8)
Gets Attributes
Description
ReflectionParameter::getAttributes(string|null $name = null, int $flags = 0): array
Returns all attributes declared on this parameter as an array of ReflectionAttribute.
Parameters
Return Values
Array of attributes, as a ReflectionAttribute object.
Examples
Basic usage
php
<?php
#[Attribute]
class Fruit {
}
#[Attribute]
class Red {
}
function fruitBasket(
#[Fruit]
#[Red]
string $apple
) { }
$reflection = new ReflectionFunction('fruitBasket');
$parameter = $reflection->getParameters()[0];
$attributes = $parameter->getAttributes();
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>The above example will output:
output
Array
(
[0] => Fruit
[1] => Red
)Filtering results by class name
php
<?php
#[Attribute]
class Fruit {
}
#[Attribute]
class Red {
}
function fruitBasket(
#[Fruit]
#[Red]
string $apple
) { }
$reflection = new ReflectionFunction('fruitBasket');
$parameter = $reflection->getParameters()[0];
$attributes = $parameter->getAttributes('Fruit');
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>The above example will output:
output
Array
(
[0] => Fruit
)Filtering results by class name, with inheritance
php
<?php
interface Color {
}
#[Attribute]
class Fruit {
}
#[Attribute]
class Red implements Color {
}
function fruitBasket(
#[Fruit]
#[Red]
string $apple
) { }
$reflection = new ReflectionFunction('fruitBasket');
$parameter = $reflection->getParameters()[0];
$attributes = $parameter->getAttributes('Color', ReflectionAttribute::IS_INSTANCEOF);
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>The above example will output:
output
Array
(
[0] => Red
)See Also
ReflectionClass::getAttributesReflectionClassConstant::getAttributesReflectionFunctionAbstract::getAttributesReflectionProperty::getAttributes