How to Prevent PHP Class Constants From Being Overridden?

Preventing PHP class const from being overridden

Starting with PHP 8.1, you can mark class constants as final (which would prevent them from being overridden in subclasses):

// PHP 8.1+
class A
{
    final public const FOO = 'foo';
}

Overriding final constants will result in an error:

// PHP 8.1+
class B extends A
{
    // Fatal error: B::FOO cannot override final constant A::FOO
    final public const FOO = 'bar';
}

This was not possible in versions of PHP prior to 8.1, as class constants could be overridden (as you can see in the example below):

class A
{
    public const FOO = 'foo';
}

class B extends A
{
    public const FOO = 'bar';
}

echo A::FOO; // 'foo'
echo B::FOO; // 'bar'

This behavior is still possible in PHP 8.1 if you don't mark class constants as final.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.