Re: Validating #[\Attribute] targets

From: Date: Sat, 26 Jul 2025 11:41:45 +0000
Subject: Re: Validating #[\Attribute] targets
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-128237@lists.php.net to get a copy of this message
On Sat, Jul 26, 2025, at 13:29, Juris Evertovskis wrote: > Hey, > > > if you are not going to call ReflectionAttribute::newInstance(), then you don't > > really need to mark the trait/interface/enum/abstract class as an attribute. > > Personally I never knew the #[\Attribute] is only required to > do ->newInstance(). > > The docs make it seem like it’s a boilerplate to have an attribute at all: > https://www.php.net/manual/en/language.attributes.overview.php > And the documented example does not call newInstance although > the attribute is defined with #[Attribute]. > > I’m also confused as the example created by Ilija > https://3v4l..org/8Lih3#v8.4.10 that would supposedly break does not > include #[Attribute] at all. But it includes an enum being used as > attribute without it using the label itself. So what would actually break? Using enums as attributes > or declaring them as such? > > Btw while reviewing the docs > https://www.php.net/manual/en/language.attributes.classes.php > I noticed that > > > It is recommended to define a separate class for each attribute. > > Recommended as opposed to what other options? I don’t think I can use a random string as an > attribute without defining it, right? So what is this recommendation steering me away from? > * * > BR, > Juris Hi Juris, You can use any identifier you’d like as an attribute, so long as you never try to get an instance of them. Since you are already reflecting on them, instead of getting an instance, you can just get the arguments and do whatever you want. We actually ended up doing this on an internal project at my last job. It was pretty powerful. — Rob

« previous php.internals (#128237) next »