PHP 8 Error to repeated an Attribute: is it possible to use attribute multiple time?

Viewed 566

I have an attribute as follow:

#[Attribute]
class State{
    public function __constractor(
        public string $name
    ){}
}

I want to add multiple states into my class as follow:

#[
   State('a'),
   State('b')
]
class StateMachine{}

Every thing is ok and I can access list of attributes as follow:

$attrs = $classReflection->getAttributes(State::class);

But the problem is, whenever I try to instant one of them, an error thrown:

$instance = $attrs[0]->newInstance();

The error is:

Error: Attribute "State" must not be repeated

Any Idea?

1 Answers

According to the official documentation you have to define your attribute differently to be able to do it that way. I used PHPStorm to verify my assumption and this should work:

Define attribute

use Attribute;

#[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_CLASS)]
class State{
    public function __construct(
        public string $name
    ){}
}

The important part here is the Attribute::IS_REPEATABLE definition. To make it work for classes you then also need to use Attribute::TARGET_CLASS.

According to docs you should also put everything in one line, when applying the attributes:

#[State('a'), State('b')]
class StateMachine{}
Related