Php 7.1返回类型提示在Laravel 5.7中失败

问题描述 投票:1回答:1

我刚刚克隆了一个我正在进行的项目的存储库。不太记得它运行的上一台机器的细节,但在这一台上它使用的是php 7.1,我升级到了Laravel 5.7。问题是,在我以前的机器中,这段代码正在运行:

class ProductsController extends Controller
{
    public function index() : Object
    {
        $products = Product::all();
        return view('products.index', ['products' => $products]);
    }
}

注意Object返回类型。

运行迁移和其他所有内容后,访问索引时我在新机器中遇到以下错误:

App \ Http \ Controllers \ ProductsController :: index()的返回值必须是App \ Http \ Controllers \ Object的实例,Illuminate \ View \ View的实例返回

这与返回类型提示是Object有关。我怎么知道的?因为如果我删除它,一切都像魅力。

为什么会这样?

php type-hinting laravel-5.7 php-7.1 laravel-controller
1个回答
2
投票

所以,对于任何感兴趣的人,我都能从不同的论坛得到答案:

只需先导入课程:

use Illuminate\View\View;

然后将其用作返回类型:

/**
 * @return View
 */
public function index(): View
{
    $products = Product::all();

    return view('products.index', ['products' => $products]);
}
© www.soinside.com 2019 - 2024. All rights reserved.