ReflectionProperty::getAttributes

(PHP 8)

ReflectionProperty::getAttributesGets Attributes

Description

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

Returns all attributes declared on this class property 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 {
}

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 Filtering results by class name

<?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 Filtering results by class name, with inheritance

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

Voir aussi

add a note add a note

User Contributed Notes

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