微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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可能没有被定义”的东西.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐