Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Cannot use unpacking in attribute argument list

Description

Attribute arguments are compiled into constant expressions, and evaluated only when the attribute is read through Reflection. The spread/unpacking operator ... needs a runtime array to unpack, which conflicts with this compile time, constant-only nature of attribute arguments.

Unpacking is therefore not allowed in the argument list of an attribute, even when the array being spread only contains constant values.

Example

<?php

#[Attribute]
class MyAttribute
{
    public function __construct(int $a, int $b) {}
}

$args = [1, 2];

#[MyAttribute(...$args)]
class X {}

?>

Alternatives

  • List each argument explicitly, instead of unpacking an array.
  • Use named arguments instead, if this improves readability.

Changed Behavior

This error may appear following an evolution in behavior, in previous versions. See