(PHP 8)
ReflectionFunctionAbstract::getAttributes — Gets Attributes
Returns all attributes declared on this function or method 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 with a class method
<?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));
?>Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
Array
(
[0] => Fruit
[1] => Red
)
Beispiel #2 Basic usage with a function
<?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));
?>Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
Array
(
[0] => Fruit
[1] => Red
)
Beispiel #3 Filtering results by class name
<?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));
?>Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
Array
(
[0] => Fruit
)
Beispiel #4 Filtering results by class name, with inheritance
<?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));
?>Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
Array
(
[0] => Red
)