这个答案似乎是
位乐于助人,同时宣布大numbe变量的函数
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
View的数组并在View中访问
但是我的功能变得非常大,所以我决定将这条线变得
非常简单
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}}