Todd Austin

Personal Blog

Using The Class Keyword in PHP and Laravel

1 year ago · 1 MIN READ
#PHP  #Laravel 5  #Workflow 

Do you hate having 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 take a look at 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 5.5 sounds old. Yes, but a lot of people still don't know about it.

<?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, I understand what it does. But how and when do I need this? When you search for the keyword in the Laravel framework, you will get over a hundred results! Seems like it is pretty 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 ahead of me? 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 identify the right class and import it for us. Not all IDE's are created equal, I simply say this because I prefer PhpStorm, which has this functionality. Your IDE may or may not do this automatically for you. Check out the documentation here for more of what PhpStorm can do for you.

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 an answer. Take some time and dig into your framework, project or programming language. You will benefit from understanding these details too.

···

Todd Austin

Web artisan with a passion for open source technologies.
comments powered by Disqus


Proudly powered by Canvas · Sign In