ReflectionParameter::getAttributes

(PHP 8)

ReflectionParameter::getAttributesGets Attributes

Description

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

Returns all attributes declared on this parameter as an array of 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

Array of attributes, as a ReflectionAttribute object.

Exemples

Exemple #1 Basic usage

<?php
#[Attribute]
class
Fruit {
}

#[
Attribute]
class
Red {
}

function
fruitBasket(
#[
Fruit]
#[
Red]
string $apple
) { }

$reflection = new ReflectionFunction('fruitBasket');
$parameter = $reflection->getParameter('apple');
$attributes = $parameter->getAttributes();
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

L'exemple ci-dessus va afficher :

Array
(
    [0] => Fruit
    [1] => Red
)

Exemple #2 Filtering results by class name

<?php
#[Attribute]
class
Fruit {
}

#[
Attribute]
class
Red {
}

function
fruitBasket(
#[
Fruit]
#[
Red]
string $apple
) { }

$reflection = new ReflectionFunction('fruitBasket');
$parameter = $reflection->getParameter('apple');
$attributes = $parameter->getAttributes('Fruit');
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

L'exemple ci-dessus va afficher :

Array
(
    [0] => Fruit
)

Exemple #3 Filtering results by class name, with inheritance

<?php
interface Color {
}

#[
Attribute]
class
Fruit {
}

function
fruitBasket(
#[
Fruit]
#[
Red]
string $apple
) { }

$reflection = new ReflectionFunction('fruitBasket');
$parameter = $reflection->getParameter('apple');
$attributes = $parameter->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

add a note add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top