Attribute class can not be used with propertyPHP-W1035
This issue is raised when attribute used with the function doesn't have 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 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)
{}
}
Now, trying to apply the attribute to a property would result in an error since property isn't in the attribute scope.
class Cars
{
#[TestAttribute('Hello World')]
private $make;
}
References
- Overview of Attributes in PHP.