(PHP 8)
ReflectionFunctionAbstract::getAttributes — Gets Attributes
$name = null, int $flags = 0): arrayReturns all attributes declared on this function or method as an array of ReflectionAttribute.
nameFiltrer les résultats pour inclure uniquement les instances de ReflectionAttribute pour les attributs correspondant à ce nom de classe.
flags
Flags pour déterminer comment filtrer les résultats, si name est fourni.
La valeur par défaut est 0 qui ne renverra que les résultats
pour les attributs qui sont de la classe name.
La seule autre option disponible est d'utiliser ReflectionAttribute::IS_INSTANCEOF,
qui utilisera plutôt instanceof pour le filtrage.
Array of attributes, as a ReflectionAttribute object.
Exemple #1 Basic usage with a class method
<?php
#[Attribute]
class Fruit {
}
#[Attribute]
class Red {
}
class Factory {
#[Fruit]
#[Red]
public function makeApple(): string
{
return 'apple';
}
}
$method = new ReflectionMethod('Factory', 'makeApple');
$attributes = $method->getAttributes();
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>
L'exemple ci-dessus va afficher :
Array
(
[0] => Fruit
[1] => Red
)
Exemple #2 Basic usage with a function
<?php
#[Attribute]
class Fruit {
}
#[Attribute]
class Red {
}
#[Fruit]
#[Red]
function makeApple(): string
{
return 'apple';
}
$function = new ReflectionFunction('makeApple');
$attributes = $function->getAttributes();
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>
L'exemple ci-dessus va afficher :
Array
(
[0] => Fruit
[1] => Red
)
Exemple #3 Filtering results by class name
<?php
#[Attribute]
class Fruit {
}
#[Attribute]
class Red {
}
#[Fruit]
#[Red]
function makeApple(): string
{
return 'apple';
}
$function = new ReflectionFunction('makeApple');
$attributes = $function->getAttributes('Fruit');
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>
L'exemple ci-dessus va afficher :
Array
(
[0] => Fruit
)
Exemple #4 Filtering results by class name, with inheritance
<?php
interface Color {
}
#[Attribute]
class Fruit {
}
#[Attribute]
class Red implements Color {
}
#[Fruit]
#[Red]
function makeApple(): string
{
return 'apple';
}
$function = new ReflectionFunction('makeApple');
$attributes = $function->getAttributes('Color', ReflectionAttribute::IS_INSTANCEOF);
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>
L'exemple ci-dessus va afficher :
Array
(
[0] => Red
)