为什么此代码显示 $req 变量未定义?

Why is this code showing $req variable undefined?

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class universityController extends Controller
{
    //

    public function getStudents(Request $req)
    {
        $students= DB::table('students')
        ->join('applicants', function ($join) {
            $join->on('students.id', '=', 'applicants.studentid')
                 ->where('applicants.scholarshipid','=', $req->scholarshipid);
        })
        ->get();
        return $students;
        // return $req->scholarshipid;
    }
}

正如@lagbox提到的,你在一个匿名函数中,它无法到达外部范围 所以要解决这个问题,你需要像这样使用 use

 public function getStudents(Request $req)
    {
        $students= DB::table('students')
        ->join('applicants', function ($join) use($req) {
            $join->on('students.id', '=', 'applicants.studentid')
                 ->where('applicants.scholarshipid','=', $req->scholarshipid);
        })
        ->get();
        return $students;
        // return $req->scholarshipid;
    }

有关 anonymous function 的更多信息,请在此处查看 docs

使用匿名变量

$students= DB::table('students')
        ->join('applicants', function ($join) use ($req) {
            $join->on('students.id', '=', 'applicants.studentid')
                 ->where('applicants.scholarshipid','=', $req->scholarshipid);
        })
        ->get();

更多 https://www.php.net/manual/en/functions.anonymous.php