ReflectionClassConstant::getAttributes
PHP function
Edit on GitHub ✎
(PHP 8)
Gets Attributes
Description
ReflectionClassConstant::getAttributes(string|null $name = null, int $flags = 0): array
Returns all attributes declared on this class constant 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 const APPLE = 'apple';
}
$classConstant = new ReflectionClassConstant('Basket', 'APPLE');
$attributes = $classConstant->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 const APPLE = 'apple';
}
$classConstant = new ReflectionClassConstant('Basket', 'APPLE');
$attributes = $classConstant->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 const APPLE = 'apple';
}
$classConstant = new ReflectionClassConstant('Basket', 'APPLE');
$attributes = $classConstant->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::getAttributesReflectionFunctionAbstract::getAttributesReflectionParameter::getAttributesReflectionProperty::getAttributes