php8.5
Home/ Manual/ reflection / reflectionclass/ ReflectionClass::getAttributes

ReflectionClass::getAttributes

PHP function Edit on GitHub ✎

(PHP 8)

Gets Attributes

Description

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

Returns all attributes declared on this class as an array of ReflectionAttribute.

Parameters

Return Values

Array of attributes, as a ReflectionAttribute object.

Examples

Basic usage

php
<?php
#[Attribute]
class Fruit {
}

#[Attribute]
class Red {
}

#[Fruit]
#[Red]
class Apple {
}

$class = new ReflectionClass('Apple');
$attributes = $class->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]
class Apple {
}

$class = new ReflectionClass('Apple');
$attributes = $class->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]
class Apple {
}

$class = new ReflectionClass('Apple');
$attributes = $class->getAttributes(Color::class, ReflectionAttribute::IS_INSTANCEOF);
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

The above example will output:

output
Array
(
    [0] => Red
)

See Also

  • ReflectionClassConstant::getAttributes
  • ReflectionFunctionAbstract::getAttributes
  • ReflectionParameter::getAttributes
  • ReflectionProperty::getAttributes

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