Using the ::class keyword in PHP and Laravel
The class keyword
Since PHP 5.5 the class keyword is used for class name resolution. This means it
returns the fully qualified
ClassName. This is extremely useful when you have namespaces, because the namespace is part of the returned name. Here
are two examples showing the returned string with a namespaced class and without.
Real application examples
Alright, this is what it does. But how and when do I need this? In fact there are quite some occasions. When you search for the keyword in the Laravel framework, you will over a hundred results! Seems that it is useful indeed.
But you can make use of it too. Let’s take a look at a relationship in a Laravel model.
Here we need to provide the related class name for the belongsTo method. Already thinking the same? Yes, we can use the keyword here too.
This way we gain two benefits. First we have to write less. Secondly, since we don’t write a string our IDE can help us find the right class and import the class. Below is a GIF showing the difference in PhpStorm.
Two things to remember from this article. First,
use the class keyword. Your workflow will benefit from it. Secondly, if
you see something in a framework you don’t quite understand,
try to find it out. Take some time and dig into your
framework, project or just programming language. You will benefit from understanding these details too.