ReflectionFunctionAbstract::getAttributes

Gets Attributes

&reftitle.description; public `array` `ReflectionFunctionAbstract::getAttributes` ``string``null```name`&null; `int` `flags` 0

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

&reftitle.parameters;
&reflection.getattributes.param.name; &reflection.getattributes.param.flags;
&reftitle.returnvalues;

Array of attributes, as a `ReflectionAttribute` object.

&reftitle.examples;

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

&example.outputs;

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

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

&example.outputs;

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

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

&example.outputs;

    Array
    (
        [0] => Fruit
    )

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

&example.outputs;

    Array
    (
        [0] => Red
    )

&reftitle.seealso;

- `ReflectionClass::getAttributes`
- `ReflectionClassConstant::getAttributes`
- `ReflectionParameter::getAttributes`
- `ReflectionProperty::getAttributes`