(PHP 8)
ReflectionProperty::getAttributes — Renvoie les attributs
Renvoie tous les attributs déclarés sur cette propriété de classe sous forme d'un tableau d'objet ReflectionAttribute.
nameflagsname 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.
Un tableau d'attributs, sous forme d'objets ReflectionAttribute.
Exemple #1 Usage basique
<?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));
?>L'exemple ci-dessus va afficher :
Array
(
[0] => Fruit
[1] => Red
)
Exemple #2 Résultats filtrés par nom de classe
<?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));
?>L'exemple ci-dessus va afficher :
Array
(
[0] => Fruit
)
Exemple #3 Résultats filtrés par nom de classe, avec héritage
<?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));
?>L'exemple ci-dessus va afficher :
Array
(
[0] => Red
)