php - 为什么我的全局变量 `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');
我在这里想念什么?
解决方案
这里没有必要global
。用于use
从父范围继承变量:
Route::get('/', function () use ($posts) {
...
});
推荐阅读
- pylint - Pylint 使用 fstring 在线提高日志记录格式插值
- sql-server - 如何真正撤消错误选择的索引创建?
- xamarin - Jenkins 无法从 dl.google.com / maven.google.com 下载 xamarin 依赖项
- azure - 如何在没有特定参数的情况下创建通用 docker 镜像
- spring-boot - WebSocket握手期间的Spring启动错误:意外的响应代码:403
- html - html和css中的div对齐
- r - 按日期排序的直方图
- excel - 循环遍历从 1 到 31 的列
- docker - GitLab Docker Runner 重用已安装的软件层
- c# - C# - 从客户端检查 TCP/IP 套接字状态