PHP 8.1 – Persistent class constants

PHP 8.1 – Persistent class constants

origami bird
It is now possible to declare a class constant as final to prevent from overriding the constant by the child class. Of course current class constant functionality remains the same.

The final modifier can be added to class constants. Doing so prevents overriding of a constant:

class Foo
{
    final public const X = "foo";
}
 
class Bar extends Foo
{
    public const X = "bar";
}
 
// Fatal error: Bar::X cannot override final constant Foo::X

Besides, interface constants would become overridable by default, and the final modifier could be used to retain the original behavior.

interface I
{
    public const X = "i";
    final public const Y = "i";
}
 
class C implements I
{
    public const X = "c"; // Overriding I::X is possible
    public const Y = "c"; // Overriding I::Y is not possible
}
 
// Fatal error: C::Y cannot override final constant I::Y

More about PHP 8.1

Read about all PHP 8.1 features and changes in here.

Leave a Comment