Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 942
Alan Storm Avatar asked Aug 19 '15 18:08

Alan Storm


People also ask

How do you fix undefined constant in laravel?

Solved undefined constant error in laravel view using single quotes. You have to pass a value with a single quote in the method. This error occurs because laravel treats it as a constant name because you did not pass the value to the method with single or double quotes.

What is a constant class?

A class constant is a field that is declared with the static and final keywords.

What does :: class mean in laravel?

Using the ::class keyword in Laravel 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.

Which syntax is correct for defining a class constant?

A class constant is declared inside a class with the const keyword.


1 Answers

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.

like image 135
Joel Hinz Avatar answered Sep 22 '22 12:09

Joel Hinz