Attribute class can not be used with methodPHP-W1031
Attribute used with the function doesn't have TARGET_METHOD
as its scope.
Therefore, an attempt to retrieve the metadata through reflection would result in a fatal error.
Apart from applying attributes to different entities in PHP, you can also define the scope of where a particular attribute should be used.
This is achieved by passing special flags to the Attribute class and these include the following: Attribute::TARGET_METHOD
, Attribute::TARGET_CLASS
, Attribute::TARGET_FUNCTION
, Attribute::TARGET_PROPERTY
, Attribute::TARGET_CLASS_CONSTANT
, Attribute::TARGET_PARAMETER
, and Attribute::TARGET_ALL
.
It is recommended to provide appropriate scope to the attribute.
Bad Practice
#[\Attribute(Attribute::TARGET_CLASS)]
class TestAttribute
{
public function __construct(public string $testArgument)
{}
}
Trying to apply this attribute to a class method to get the metadata through reflection will throw a fatal error.
class MyClass
{
#[TestAttribute('Hello World')]
public function index()
{
}
}
$reflection = new \ReflectionMethod(MyClass::class, 'index');
$methodAttributes = $reflection->getAttributes();
print_r($methodAttributes[0]->newInstance()->testArgument);
References
- Overview of Attributes in PHP.