PHP Laravel:理解这个闭包

PHP Laravel:理解这个闭包,php,laravel,closures,Php,Laravel,Closures,我从Laravel文档中得到了以下片段: DB::table('users') ->whereExists(function ($query) { $query->select(DB::raw(1)) ->from('orders') ->whereRaw('orders.user_id = users.id');

我从Laravel文档中得到了以下片段:

DB::table('users')
            ->whereExists(function ($query) {
                $query->select(DB::raw(1))
                      ->from('orders')
                      ->whereRaw('orders.user_id = users.id');
            })
            ->get();
我需要了解两件事

  • 闭包的
    $query
    参数来自哪里?我怀疑引擎盖下发生了我不明白的事情。函数接受1个参数,
    $query
    ,但它来自何处,该函数如何知道该参数中包含什么,传递给函数的是什么
  • 这个闭包似乎没有返回值,没有
    return
    语句。那么
    whereExists
    方法如何知道闭包的返回值呢
  • 参考资料来源:

    正如您所见,闭包被视为回调

    所以
    whereExists
    $query
    传递给它
    $query
    是self(Builder)类的实例,因此闭包中的代码只是更新对象

    /**
     * Add an exists clause to the query.
     *
     * @param  \Closure $callback
     * @param  string   $boolean
     * @param  bool     $not
     * @return $this
     */
    public function whereExists(Closure $callback, $boolean = 'and', $not = false)
    {
        $query = $this->forSubQuery();
        // Similar to the sub-select clause, we will create a new query instance so
        // the developer may cleanly specify the entire exists query and we will
        // compile the whole thing in the grammar and insert it into the SQL.
        call_user_func($callback, $query);
        return $this->addWhereExistsQuery($query, $boolean, $not);
    }
    

    阅读本手册页面可能对#1阅读手册页面-查询生成器有很大帮助-