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

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

WBOY
WBOYOriginal
2016-12-05 13:44:242082browse

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>

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>

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.

Statement:
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