Laravel - Why the constant `:: 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 changing use of predefined / magic constant ::class

 \App\Console\Commands\Inspire::class 

functionally different from just using a class name?

 \App\Console\Commands\Inspire 
+5
source share
2 answers

No, using ::class in a class returns the full name of the class, so this is the same as writing 'App\Console\Commands\Inspire' (in quotation marks, since this is a string). The class keyword is new to PHP 5.5.

In this example, it looks silly, but it can be useful, for example, in testing or defining relationships. For example, if I have an Article class and an ArticleComment class, I can finish the job

 use Some\Long\Namespace\ArticleComment; class Article extends Model { public function comments() { return $this->hasMany(ArticleComment::class); } } 

Link: PHP docs .

+6
source

This does not matter for the execution of the code, but the ::class constant is most useful with development tools. If you use the class name, you must write it as the string '\App\Console\Commands\Inspire' - this means:

  • IDE auto complete
  • No support for automatic refactoring ("rename class")
  • Without namespace permission
  • No way to automatically detect usage (IDE) or dependencies (pDepend)

Note: Prior to PHP 5.5, I used the __CLASS constant for most of my classes for this purpose:

 class X { const __CLASS = __CLASS__; } 
+6
source

All Articles