[php-src] Issue #8728: Add `getFirstAttribute()` to `ReflectionProperty`
| From: | SamMousa | Date: | Wed, 08 Jun 2022 10:12:41 +0000 |
| Subject: | [php-src] Issue #8728: Add `getFirstAttribute()` to `ReflectionProperty` | ||
| Groups: | php.bugs | ||
| Request: | Send a blank email to php-bugs+get-241683@lists.php.net to get a copy of this message | ||
Issue: https://github.com/php/php-src/issues/8728
Author: SamMousa
### Description
Currently the only way to retrieve property attributes is to use
getAttributes(), which
always returns an array.
In many cases we know an attribute can not be repeated but code handling the attributes still needs
to deal with it.
This leads to ugly code like below, or worse assigning then checking.
```php
($reflectionProperty->getAttributes(SomeAttribute::class)[0] ??
null)?->newInstance()->doSomething();
```
If we had a simple getFirstAttribute(string $className): null|ReflectionAttribute our
code would be come more readable and communicate our intentions more clearly:
```php
$reflectionProperty->getFirstAttribute(SomeAttribute::class)?->newInstance()->doSomething();
```
While writing this I realize that this request can be broadened to include any target for attributes
(ReflectionMethod, ReflectionClass etc).