Что такое атрибуты (Attributes)?

Ответ
// Объявление атрибута
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class Route {
    public function __construct(
        public string $path,
        public string $method = 'GET',
    ) {}
}

// Использование
class UserController {
    #[Route('/users', method: 'GET')]
    #[Route('/users/list', method: 'GET')]
    public function list(): Response { /* ... */ }
}

// Чтение через Reflection
$ref = new ReflectionMethod(UserController::class, 'list');
$attrs = $ref->getAttributes(Route::class);
foreach ($attrs as $attr) {
    $route = $attr->newInstance();
    echo "$route->method $route->path\n";
}

Атрибуты заменяют docblock-аннотации (@Route). Нативная поддержка PHP, проверка типов, IDE-подсказки.

🧠Квиз 🏆Лидеры 🎯Собесед. 📖Вопросы 📚База зн.