php警告变量没有定义,php – 处理未定义的变量

我有这个索引函数与变量$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.如果任何变量不存在,则传递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();

...

}

解决方法:

据我所知,你唯一的问题是$checkforid.只需将其初始化为空数组:

$checkforid = [];

if(Auth::check())

{

...

$checkforid[]= ...

...

}

一个好的IDE会警告并告诉你类似“$checkforid可能没有被定义”的东西.

标签:php,laravel

来源: https://codeday.me/bug/20190623/1267885.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值