以数据库事务为例:
    方法1:

    1. // Should contain any messages to pass back to the user
    2. $results = [];
    3. // Contains the total records inserted
    4. $total = 0;
    5. DB::transaction(function() use($csv_file, &$results, &$total) {
    6. // Some Code ...
    7. $total++;
    8. $results[] = 'Row 10 has some weird data...';
    9. });
    10. return view('plan.import')
    11. ->with('results', $results)
    12. ->with('total', $total);

    函数内部所做的更改将反映在变量中,因为&创建变量的引用(传递变量引用)而不是按值传递变量。检查通过参考手册传递

    方法2:

    // Should contain any messages to pass back to the user
    $results = [];
    
    // Contains the total records inserted
    $total = 0;
    
    $array = DB::transaction(function() use($csv_file, $results, $total) {
    
        // Some Code ...
    
        $total++;
        $results[] = 'Row 10 has some weird data...';
        return compact('total', 'results');
    });
    
    return view('plan.import')
    ->with('results', $array['results'])
    ->with('total', $array['total']);
    

    从闭包内部返回变量。