Skip to main content

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.

A final class constant in PHP is a constant declared with the final modifier within a class or interface, which explicitly prevents child classes or implementing classes from overriding its value. Introduced in PHP 8.1, this feature enforces strict immutability of the constant’s value across the entire inheritance hierarchy. Prior to PHP 8.1, class constants could be freely redefined by child classes. The final modifier alters this default behavior, ensuring the constant remains identical to its original definition throughout all derived contexts.

Syntax

The final keyword is placed before or after the visibility modifier, preceding the const keyword.
class Configuration {
    final public const MAX_CONNECTIONS = 100;
    protected final const TIMEOUT = 30;
}

Inheritance Mechanics

When a class extends a parent class containing a final constant, any attempt to redeclare that constant in the child class will result in a compile-time Fatal error.
class BaseClass {
    final public const ENVIRONMENT = 'production';
}

class ChildClass extends BaseClass {
    // Fatal error: ChildClass::ENVIRONMENT cannot override final constant BaseClass::ENVIRONMENT
    public const ENVIRONMENT = 'development'; 
}

Visibility Constraints

The final modifier interacts specifically with visibility modifiers (public, protected, private):
  • Public and Protected: The final modifier is fully supported and enforces the non-override rule in child classes.
  • Private: The final modifier cannot be applied to private constants. Because private constants are restricted to the scope of the declaring class and are invisible to child classes, they inherently cannot be overridden. Attempting to declare a final private const will throw a Fatal error.
class InvalidClass {
    // Fatal error: Private constant InvalidClass::SECRET cannot be declared final
    final private const SECRET = 'token'; 
}

Interface Implementation

The final modifier can also be applied to constants within an interface. When a class implements an interface containing a final constant, the implementing class is prohibited from redefining it.
interface DatabaseContract {
    final public const DEFAULT_PORT = 3306;
}

class MySQLAdapter implements DatabaseContract {
    // Fatal error: MySQLAdapter::DEFAULT_PORT cannot override final constant DatabaseContract::DEFAULT_PORT
    public const DEFAULT_PORT = 5432; 
}
Note: In PHP, interface constants are implicitly public. If a visibility modifier is omitted in an interface, it defaults to public, and the final modifier will still operate as expected.
Master PHP with Deep Grasping Methodology!Learn More