PHP 8.1 : Final class constants
25, September 2021

Before PHP 8.1, we were allowed to override parent class constants on child class. It can create some confusion since constants are not supposed to be changed.

To deal with it, PHP 8.1 introduces final keyword to define class constant as final or non-overridable.


class Foo {
  public const ABC = 'some';
}

class Bar extends Foo {
  public const ABC = 'thing'; // php allows to override this const
}

// but if we use final constants
class Foo {
  final public const ABC = 'some';
}

class Bar extends Foo {
  public const ABC = 'thing'; // not allowed
}

// Fatal error: Bar::ABC cannot override final constant Foo::ABC


We can define final constants in interfaces too:

interface Manager {
  final public const FOO = 'Bazz';
}


For reflection, ReflectionClassConstant::isFinal() method is available to detect if a constant is final.


RFC: https://wiki.php.net/rfc/final_class_const


Write comment about this article: