我有一個變量$product
,$categories
,$most_views
,$show
,$check
,$checkforid
該指數函數。處理未定義的變量
public function index()
{
$products=Product::where(['status'=>'1'])->orderBy('most_viewed','desc')->with('category')->get();
$categories=Category::all();
$mostviews=Product::where(['status'=>'On sale'])->orderBy('most_viewed','desc')->limit(10)->get();
$show=Product::orderBy('most_viewed','desc')->with('category')
->with('user')
->with('productbrand.brand')
->first();
if(Auth::check())
{
$check=Watchlist::where(['user_id'=>Auth::user()->id])->get()->toArray();
foreach($check as $che)
{
$checkforid[]=$che['product_id'];
}
}
return View('product.index',['products'=>$products,'mostviews'=>$mostviews,'show'=>$show,'checkforid'=>$checkforid,'categories'=>$categories]);
}
如果這些變量的亙古不變的存在,
return View('product.index',['products'=>$products,'mostviews'=>$mostviews,'show'=>$show,'checkforid'=>$checkforid,'categories'=>$categories]);
總會有一個錯誤未定義的變量和整個索引頁會受到影響。所以我想跳過不存在的變量。這是最好的解決方案是什麼?
直到現在,我已經初始化所有變量爲null.so,如果任何變量不存在null傳遞。這是一個好習慣嗎?
public function index()
{
$products=null;
$show=null;
$check=null;
$checkforid=null;
$mostviews=null;
$categories=null;
$products=Product::where(['status'=>'1'])->orderBy('most_viewed','desc')->with('category')->get();
$categories=Category::all();
$mostviews=Product::where(['status'=>'On sale'])->orderBy('most_viewed','desc')->limit(10)->get();
...
}
可能重複http://stackoverflow.com/questions/17767094/check-if-array-value-isset-and- is-null –
if(isset($ someVar))檢查 –