Attribute “%s” cannot target %s (allowed targets: %s)

Description

Attributes are built with a specific target, and may not be applicable to any structure. For example, the native ReturnTypeWillChange targets only methods, and not properties.

With a custom structure, the error is shown when requesting an instance of the attribute. Otherwise, this error remains silent, and the structure may be used without error.

With a PHP native attribute, the engine decides when it makes use of it.

Example

<?php

// example with a native PHP attribute
class Foo
{
    #[ReturnTypeWillChange]
    public int $bar;
}

#[Attribute(Attribute::TARGET_FUNCTION | Attribute::TARGET_METHOD)]
class X { }

// the object is created. It may be used without error.
$ref = new ReflectionObject(new #[X] class() { });
$attr = $ref->getAttributes()[0];

try {
    $attr->newInstance();
} catch (\Throwable $e) {
    print $e->getMessage();
}

?>

Solutions

  • Remove the attribute restrictions.

  • Update the attribute to target the requested feature.

  • Remove the attribute from the forbidden feature.

  • Create another the attribute for the feature.

Static Analysis

This error may be tracked down with the following static analysis rules: Php/WrongAttributeConfiguration.