以数据库事务为例:
方法1:
// Should contain any messages to pass back to the user$results = [];// Contains the total records inserted$total = 0;DB::transaction(function() use($csv_file, &$results, &$total) {// Some Code ...$total++;$results[] = 'Row 10 has some weird data...';});return view('plan.import')->with('results', $results)->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']);
从闭包内部返回变量。
