Alana Storm
Alana Storm

Reputation: 166066

Laravel -- Why the `::class` Constant

In Laravel 5.1, the kernel for the CLI class looks something like this

#File: app/Console/Kernel.php
class Kernel extends ConsoleKernel
{
    //...    
    protected $commands = [
        \App\Console\Commands\Inspire::class,
    ];
    //...
}

Is the change to using the predefined/magic constant ::class

\App\Console\Commands\Inspire::class

functionally different than simply using the class name?

\App\Console\Commands\Inspire

Upvotes: 5

Views: 1428

Answers (2)

Fabian Schmengler
Fabian Schmengler

Reputation: 24551

For executing the code it doesn't make a difference, but the ::class constant is most useful with development tools. If you use the class name you have to write it as string '\App\Console\Commands\Inspire' - that means:

  1. No IDE auto completion
  2. No suport of automatic refactoring ("rename class")
  3. No namespace resolving
  4. No way to automatically detect usages (IDE) or dependencies (pDepend)

Side note: Before PHP 5.5 came out, I used to define a constant __CLASS in most of my own classes for exactly this purpose:

class X {
    const __CLASS = __CLASS__;
}

Upvotes: 6

Joel Hinz
Joel Hinz

Reputation: 25384

Nope, using ::class on a class returns the fully qualified class name, so it's the same thing as writing 'App\Console\Commands\Inspire' (in quotes, since it's a string). The class keyword is new to PHP 5.5.

It looks silly in this example, but it can be useful in e.g. testing or in defining relations. For instance, if I have an Article class and an ArticleComment class, I might end up doing

use Some\Long\Namespace\ArticleComment;

class Article extends Model {

    public function comments()
    {
        return $this->hasMany(ArticleComment::class);
    }

}

Reference: PHP Docs.

Upvotes: 6

Related Questions