首页 > 解决方案 > 为什么我的全局变量 `null` 在 `web.php` 文件中的函数内?

问题描述

来自 Javascript 世界,我已经阅读了 PHP 全局变量以及如何使用global关键字在函数中引用它们。
但是当我试图dd($posts)返回时null。这是代码:

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

$posts = [
    [
        'image'       => 'https://picsum.photos/id/900/1600/900',
        'title'       => 'Post title',
        'author'      => 'Author',
        'link'        => '#0',
    ],
    [
        'image'       => 'https://picsum.photos/id/900/1600/900',
        'title'       => 'Post title',
        'author'      => 'Author',
        'link'        => '#0',
    ],
];

Route::get('/', function () {
    global $posts;
    dd($posts); // returns null
    return view('pages.home', compact('posts'));
})->name('home');

我在这里想念什么?

标签: phplaravel

解决方案


这里没有必要global。用于use从父范围继承变量:

Route::get('/', function () use ($posts) {
    ...
});

推荐阅读