Attribute class can not be used with parameter/propertyPHP-W1024
Attribute used with the parameter
/ property
doesn't have TARGET_PARAMETER
/ TARGET_PROPERTY
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 and these includes 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)
{}
}
Now, trying to apply the attribute to a function would result in an error since function isn't in the attribute scope.
class Index
{
public function doMath(
#[TestAttribute('Hello World')]
$squares
)
{}
}
References
- Overview of Attributes in PHP.