Mirasan
Mirasan

Reputation: 259

Why aliases use ::class at the end in Laravel

Good day to all, I am beginner Laravel developer and wanted to ask you about why aliases in Laravel use ::class at the end for eaxmple: 'DB' => Illuminate\Support\Facades\DB::class, that is, I know ::class means it will return fully qualified name of a class in a string format. Well, does it mean that if I use DB::insert() then it will be equivalent to Illuminate\Support\Facades\DB::insert(). So, the use of ::class means I do not have to write fully qualified name of a class.

Upvotes: 0

Views: 113

Answers (1)

Tobias K.
Tobias K.

Reputation: 3082

\DB::insert is equivalent to a call to \Illuminate\Support\Facades\DB::insert(), but not because the ::class syntax.

It would also work if the line in aliases was a string, these are all the same:

use Illuminate\Support\Facades\DB as DBFacade;

    'DB' => 'Illuminate\Support\Facades\DB', // (string) Illuminate\Support\Facades\DB
    'DB' => \Illuminate\Support\Facades\DB::class, // (string) Illuminate\Support\Facades\DB
    'DB' => DBFacade::class, // (string) Illuminate\Support\Facades\DB

::class is just a convenience feature, see this answer for 2 reasons it is helpful.

The real reason you can call the "aliased" name (without a namespace) is because Laravel adds a method to the autoloader that will load the class if requested by its aliased name using either PHPs class_alias or an auto-generated stub class, based on the aliases array from your config file.

Upvotes: 2

Related Questions