好的,这是一个相当具体的问题,我不一定期待回应,但如果有人能指出我正确的答案方向,那就太好了。所以我一直在阅读 Laravel 的文档,我遇到了一个部分( http://laravel.com/docs/5.1/responses#basic-responses ),它有以下关于生成响应对象的建议:
Returning a full Response instance allows you to customize the response's HTTP status code and headers. A Response instance inherits from the Symfony\Component\HttpFoundation\Response class, providing a variety of methods for building HTTP responses:
use Illuminate\Http\Response; Route::get('home', function () { return (new Response($content, $status)) ->header('Content-Type', $value); });
For convenience, you may also use the response helper:
Route::get('home', function () { return response($content, $status) ->header('Content-Type', $value); });
所以我的问题是,关于后一个代码示例,他们为什么不再需要包含
use Illuminate\Http\Response;
进口?或者更具体地说, response() 函数中发生了什么,这意味着我们不必这样做?
最佳答案
这实际上是标准的 PHP namespacing ,而不是 Laravel 正在做的一些独特的事情。 use
仅在使用命名空间类时才需要语句。response()
辅助函数没有命名空间(它位于全局命名空间中),所以它不需要 use
陈述。Illuminate\Http\Response
类是命名空间的,所以它需要一个 use
陈述。
Laravel 辅助函数位于 vendor/laravel/framework/src/Illuminate/Foundation/helpers.php ,并且此文件没有设置命名空间。如果是这样,你会看到 namespace Illuminate/Foundation
在它的顶部。
关于php - Laravel 工厂辅助函数如何在命名空间方面工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31645027/