5

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 Answer 1

10

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{}
Sign up to request clarification or add additional context in comments.

2 Comments

Im trying to get these to work. Thing is , I dont want them to be repeatable, but its not throwing any errors
@theMyth You probably forgot to call newInstance(). Only then will they be checked for duplication.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.