Syntax
The type declaration is placed after the visibility modifier (if present) and theconst 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)
voidandnever: 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 aFatal 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 asmixed. 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





