Can Class Constants be Type Hinted in PHP?

Starting from PHP 8.3, you can type hint class constants, for example, like so:

// PHP 8.3+
class A
{
    const string FOO = 'bar';

    // ...
}

You can specify any type for constant declarations, including union and intersection types. However, void, callable, and never are not supported.

Please note that when overriding class constants, they follow a covariant behavior, allowing narrower types to be used in subclasses while disallowing wider types.


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.