ReflectionProperty::getAttributes
PHP function
Edit on GitHub ✎
(PHP 8)
Gets Attributes
Description
ReflectionProperty::getAttributes(string|null $name = null, int $flags = 0): array
Returns all attributes declared on this class property 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 {
}
class Basket {
#[Fruit]
#[Red]
public string $apple = 'apple';
}
$property = new ReflectionProperty('Basket', 'apple');
$attributes = $property->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 {
}
class Basket {
#[Fruit]
#[Red]
public string $apple = 'apple';
}
$property = new ReflectionProperty('Basket', 'apple');
$attributes = $property->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 {
}
class Basket {
#[Fruit]
#[Red]
public string $apple = 'apple';
}
$property = new ReflectionProperty('Basket', 'apple');
$attributes = $property->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::getAttributesReflectionParameter::getAttributes