为什么我的全局变量' null '内部函数在' web.php '文件?



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

<?php
use IlluminateSupportFacadesRoute;
/*
|--------------------------------------------------------------------------
| 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');

我在这里错过了什么?

这里不需要global。使用use从父作用域继承变量:

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

只需添加use($posts)。你可以在你的路由中使用下面的代码:

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