这个答案似乎是
有点帮助同时在函数中声明大量变量
Laravel 5.7.*
举例
public function index()
{
$activePost = Post::where('status','=','active')->get()->count();
$inActivePost = Post::where('status','=','inactive')->get()->count();
$yesterdayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(-1))->get()->count();
$todayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(0))->get()->count();
return view('dashboard.index')->with('activePost',$activePost)->with('inActivePost',$inActivePost )->with('yesterdayPostActive',$yesterdayPostActive )->with('todayPostActive',$todayPostActive );
}
当您看到返回的最后一行时,它看起来不太好
当你的项目变得越来越大时它不好
所以
public function index()
{
$activePost = Post::where('status','=','active')->get()->count();
$inActivePost = Post::where('status','=','inactive')->get()->count();
$yesterdayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(-1))->get()->count();
$todayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(0))->get()->count();
$viewShareVars = ['activePost','inActivePost','yesterdayPostActive','todayPostActive'];
return view('dashboard.index',compact($viewShareVars));
}
如您所见,所有变量都声明为 $viewShareVars 数组并在视图中访问
但我的功能变得非常大,所以我决定制作这条线
非常简单
public function index()
{
$activePost = Post::where('status','=','active')->get()->count();
$inActivePost = Post::where('status','=','inactive')->get()->count();
$yesterdayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(-1))->get()->count();
$todayPostActive = Post::whereDate('created_at', Carbon::now()->addDay(0))->get()->count();
$viewShareVars = array_keys(get_defined_vars());
return view('dashboard.index',compact($viewShareVars));
}
原生php函数get_defined_vars()从函数中获取所有定义的变量
和array_keys 将获取变量名
所以在您看来,您可以访问函数内所有声明的变量
作为{{$todayPostActive}}