Home > Backend Development > PHP Tutorial > Why do we use ::class syntax in Laravel source code?

Why do we use ::class syntax in Laravel source code?

WBOY
Release: 2023-03-03 10:34:02
Original
2130 people have browsed it

Since PHP 5.5, the keyword class can also be used for class name resolution. Using ClassName::class you can get a string containing the fully qualified name of the class ClassName. This is especially useful for classes that use namespaces.

<code>$app->singleton(
    Illuminate\Contracts\Http\Kernel::class,
    App\Http\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);
</code>
Copy after login
Copy after login

Since the fully qualified name of the class has been written in this bootstrap/app.php code, why do we need to use the ::class syntax?

Reply content:

Since PHP 5.5, the keyword class can also be used for class name resolution. Using ClassName::class you can get a string containing the fully qualified name of the class ClassName. This is especially useful for classes that use namespaces.

<code>$app->singleton(
    Illuminate\Contracts\Http\Kernel::class,
    App\Http\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);
</code>
Copy after login
Copy after login

Since the fully qualified name of the class has been written in this bootstrap/app.php code, why do we need to use the ::class syntax?

Someone on Zhihu gave the correct answer https://www.zhihu.com/questio...

This is the type AppHttpKernel, which is an object type of a class;

This is the class name string of the class AppHttpKernel::class, which is a string.

For this question, you first need to understand Laravel’s container concept.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template