Using the ::class keyword in PHP and Laravel
#Have you ever seen PHP frameworks or projects use the ::class keyword and wondered what it does and where it comes from? Let's find out!
Do you hate to write fully qualified class names in strings too? Have you ever seen PHP frameworks use the ::class keyword and wondered what it does and where it comes from? Let's find out how these two things fit together!
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.
<?php
class User {
}
echo User::class; // returns User
<?php
namespace App\Models;
class User {
}
echo User::class; // returns App\Models\User
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.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo('App\Models\User');
}
}
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.
<?php
return $this->belongsTo(User::class);
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.
Conclusion
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.