(PHP 8)
ReflectionClassConstant::getAttributes — Gets Attributes
Returns all attributes declared on this class constant as an array of ReflectionAttribute.
nameDie Ergebnisse werden so gefiltert, dass nur ReflectionAttribute-Instanzen für Attribute mit diesem Klassennamen enthalten sind.
flags
Flags, die festlegen, wie die Ergebnisse gefiltert werden sollen, wenn
name angegeben wird.
Die Voreinstellung ist 0, was nur Ergebnisse für die
Attribute der Klasse name liefert.
Die einzige andere Möglichkeit ist die Verwendung von
ReflectionAttribute::IS_INSTANCEOF, wodurch stattdessen
instanceof zum Filtern verwendet wird.
Array of attributes, as a ReflectionAttribute object.
Beispiel #1 Basic usage
<?php
#[Attribute]
class Fruit {
}
#[Attribute]
class Red {
}
class Basket {
#[Fruit]
#[Red]
public const APPLE = 'apple';
}
$classConstant = new ReflectionClassConstant('Basket', 'APPLE');
$attributes = $classConstant->getAttributes();
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
Array
(
[0] => Fruit
[1] => Red
)
Beispiel #2 Filtering results by class name
<?php
#[Attribute]
class Fruit {
}
#[Attribute]
class Red {
}
class Basket {
#[Fruit]
#[Red]
public const APPLE = 'apple';
}
$classConstant = new ReflectionClassConstant('Basket', 'APPLE');
$attributes = $classConstant->getAttributes('Fruit');
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
Array
(
[0] => Fruit
)
Beispiel #3 Filtering results by class name, with inheritance
<?php
interface Color {
}
#[Attribute]
class Fruit {
}
#[Attribute]
class Red implements Color {
}
class Basket {
#[Fruit]
#[Red]
public const APPLE = 'apple';
}
$classConstant = new ReflectionClassConstant('Basket', 'APPLE');
$attributes = $classConstant->getAttributes('Color', ReflectionAttribute::IS_INSTANCEOF);
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
Array
(
[0] => Red
)