Attributes work on functions, classes, class constants, properties, methods and parameters, but not on global constants declared with const. This RFC from Daniel Scherzer adds support there too, which also means you can mark a constant with #[\Deprecated].

It only covers constants declared with const MY_CONST = 5;. Constants created with define() aren't included.

Show me

Here is the RFC's example:

// This is okay
#[\MyAttribute]
const Example1 = 1;

// This is an error
#[\MyAttribute]
const Example2 = 2,
    Example3 = 3;

An attribute only works on a constant declared on its own. If one const statement declares several constants, adding an attribute is a compile error, which the RFC says avoids confusing code.

What it adds

  • Attribute::TARGET_CONSTANT, so an attribute class can declare that it applies to constants.
  • Attribute::TARGET_ALL now includes constants as well.
  • ReflectionConstant::getAttributes(), which reads the attributes at runtime and works like the other getAttributes() methods.
  • #[\Deprecated] can now go on a constant, and using that constant then emits a deprecation notice.

What it means for existing code

Code that works today keeps working. An attribute on a constant used to be an error, so no working code has one.

A few things may need updates:

  • If you wrote an attribute with Attribute::TARGET_ALL that doesn't make sense on constants, you may want to narrow its targets.
  • If your code assumes ReflectionConstant::isDeprecated() is always false for your own constants, that's no longer true.
  • Static analyzers and IDEs need to learn that this syntax is now allowed.

The vote

It passed 26 to 0, clearing the two-thirds majority it needed. The poll offered only Yes and No, and voting closed on January 6, 2025. It was proposed for the next PHP version (8.5 or 9.0), and the page marks it as implemented.