Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Using ::class static class keyword in PHP

If you’ve worked with modern frameworks such as Laravel, you might have seen this keyword ::class be used extensively throughout the application.

So, for instance, in Laravel, in app/Http/Kernel.php, there’s a property $middleware which contains all the middlewares that the application is using. Here’s how the property looks like.

protected $middleware = [
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::class,
];

So, what does the ::class keyword exactly do in this case? Well, when you append the ::class keyword to any class, PHP will resolve it into a string which contains the fully qualified name of the class.

So, the following,

\App\Http\Middleware\CheckForMaintenanceMode::class

is equivalent to…

'App\Http\Middleware\CheckForMaintenanceMode'

Usefulness

One should use the ::class instead of using the fully qualified name as a string, as it can help in navigating to the class from the IDE such as PhpStorm right from where it’s defined.

Apart from this, it helps in reducing the human error while trying to write the fully qualified class names as a string as you just need to import the class which is again very easy in PhpStorm.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?