ReflectionFunctionAbstract::getAttributes

(PHP 8)

ReflectionFunctionAbstract::getAttributesRenvoie les attributs

Description

public function ReflectionFunctionAbstract::getAttributes(?string $name = null, int $flags = 0): array

Renvoie tous les attributs déclarés sur cette fonction ou méthode sous forme d'un tableau de ReflectionAttribute.

Liste de paramètres

name
Filtrer 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.

Valeurs de retour

Un tableau d'attributs, sous forme d'objet ReflectionAttribute.

Exemples

Exemple #1 Utilisation basique avec une méthode de classe

<?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 Utilisation basique avec une fonction

<?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 Résultats filtrés par nom de classe

<?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 Résultats filtrés par nom de classe, avec héritage

<?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
)

Voir aussi