A class constant is an immutable, statically-bound value defined within the scope of a class, interface, or trait. Unlike instance properties, class constants are allocated once per class rather than per object instantiation, and their values cannot be altered at runtime after initial compilation.Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
Declaration and Syntax
Class constants are defined using theconst keyword. As of PHP 7.1, they support visibility modifiers (public, protected, private), with public being the default. As of PHP 8.3, class constants support explicit type declarations.
Resolution and Access
Because constants are bound to the class structure itself, they are accessed using the Scope Resolution Operator (::, also known as Paamayim Nekudotayim), rather than the object operator (->).
Internal Access
Within the class hierarchy, constants are referenced using scope identifiers:self::: Resolves to the class in which the code is explicitly written (Early Binding).static::: Resolves to the class that was called at runtime, enabling Late Static Binding.parent::: Resolves to the constant defined in the immediate parent class.
External Access
From outside the class scope, constants are accessed using the fully qualified class name, a variable containing the class name, an object instance, or dynamically via a variable containing the constant name.The Magic ::class Constant
PHP automatically provides a magic class constant for all classes, interfaces, and traits. It resolves to the fully qualified class name (FQCN) as a string at compile time. As of PHP 8.0, ::class can also be evaluated on object instances to resolve their runtime class name.
Technical Constraints
- Constant Expressions: The value assigned to a class constant must be a constant expression. It cannot be the result of a variable, a property, or a standard function call evaluated at runtime. It can, however, be a scalar expression (e.g., bitwise operations, mathematical operations) or an array.
- Interfaces and Traits: Interfaces can declare constants, which are inherited by implementing classes. Traits can also declare constants (as of PHP 8.2), which are flattened into the composing class during compilation.
- Overriding and Invariance: A child class can override a parent’s constant provided the visibility rules are respected (e.g., a
protectedconstant can be overridden aspublicorprotected, but notprivate). However, as of PHP 8.3, typed class constants are strictly invariant. When overriding a typed constant in a child class, the type must match the parent exactly; it cannot be widened or narrowed. - Final Constants: As of PHP 8.1, constants can be declared
finalto strictly prevent overriding in child classes.
Master PHP with Deep Grasping Methodology!Learn More





