Skip to main content
Typed class constants, introduced in PHP 8.3, enforce strict type declarations on constants defined within classes, interfaces, traits, and enumerations. This mechanism ensures that the value assigned to a constant strictly adheres to a specified data type at compile time, preventing unintended type coercion or invalid overrides in inheritance hierarchies.

Syntax

The type declaration is placed after the visibility modifier (if present) and the const keyword, preceding the constant name.

Type Support and Restrictions

Typed constants support the majority of PHP’s type system, including:
  • Scalar types: int, float, string, bool
  • Compound types: array, iterable, object
  • Special types: mixed
  • Complex types: Union types (e.g., int|float) and Intersection types (e.g., ClassA&InterfaceB)
Unsupported Types:
  • void and never: Constants must inherently hold a value, making these types logically invalid.
  • callable: Excluded from property and constant type declarations due to context-dependent execution behavior.

Compile-Time Enforcement

Type validation for constants occurs strictly at compile time. If the assigned value does not match the declared type, PHP throws a Fatal error. Unlike variable assignments or function returns in non-strict modes, PHP will not perform implicit type coercion for typed constants, regardless of the declare(strict_types=1); directive.

Inheritance and Variance

When a child class or an implementing interface overrides a typed constant, PHP enforces covariance. The overriding constant must declare a type that is equal to or narrower than the parent constant’s type. Widening the type results in a compile-time fatal error.

Untyped Constants in Inheritance

If a parent class defines an untyped constant, PHP implicitly treats its type as mixed. A child class can override this untyped constant with a strictly typed constant, as narrowing from mixed to a specific type satisfies the rules of covariance.
Tired of Poor PHP Skills? Fix That With Deep Grasping!Learn More