How to Prevent PHP Class Constants 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.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.