Re: Reflection*::hasAttribute()
| From: | Robin Chalas | Date: | Thu, 13 Jul 2023 05:08:14 +0000 |
| Subject: | Re: Reflection*::hasAttribute() | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-120800@lists.php.net to get a copy of this message | ||
> I think that would require an RFC.
Alright, thanks.
> To clarify, you're proposing to replace this:
>count((new ReflectionClass(Beep::class))->getAttributes(Ignore::class)) == true
>with
>(new ReflectionClass(Beep::class))->hasAttribute(Ignore::class)
> Right?
Correct.
> That doesn't seem like a huge improvement.
Probably not a huge one indeed, yet it makes the intent more clear for the use case at hand.
Given such attributes are getting more and more common in userland, not only in frameworks, I tend
to think it's worth considering.
>Actually,
>
>if ((new ReflectionClass(Beep::class))->getAttributes(Ignore::class))
>
>would work as well, so basically:
>
>$rc->hasAttribute(Ignore::class) === (bool)
>$rc->getAttributes(Ignore::class);
Yes, (ab)using
getAttributes() for that purpose is certainly not a big deal, just like
using strpos() for word detection was not.
But str_contains() came up as it’s semantically better.
Probably worth adding that such method looks consistent with other parts of the Reflection API like
hasProperty(), hasMethod(), hasConstant or
implementsInterface().
About other languages, Java has isAnnotationPresent() and C# has
Attribute.IsDefined() - both serving the exact same purpose.
-- Robin Chalas