php8.5
Home/ Manual/ reflection / reflectionfunctionabstract/ ReflectionFunctionAbstract::getAttributes

ReflectionFunctionAbstract::getAttributes

PHP function Edit on GitHub ✎

(PHP 8)

Gets Attributes

Description

ReflectionFunctionAbstract::getAttributes(string|null $name = null, int $flags = 0): array

Returns all attributes declared on this function or method as an array of ReflectionAttribute.

Parameters

Return Values

Array of attributes, as a ReflectionAttribute object.

Examples

Basic usage with a class method

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

The above example will output:

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

Basic usage with a function

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

The above example will output:

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

Filtering results by class name

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

The above example will output:

output
Array
(
    [0] => Fruit
)

Filtering results by class name, with inheritance

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

The above example will output:

output
Array
(
    [0] => Red
)

See Also

  • ReflectionClass::getAttributes
  • ReflectionClassConstant::getAttributes
  • ReflectionParameter::getAttributes
  • ReflectionProperty::getAttributes

Source: reference/reflection/reflectionfunctionabstract/getattributes.xml · from the official PHP manual (php/doc-en)