php 将数据传递给 Laravel 4 中的闭包

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14482102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:22:59  来源:igfitidea点击:

Passing data to a closure in Laravel 4

phplaravellaravel-4

提问by Benjamin Gonzalez

I'm trying to use the Mail Class in Laravel 4, and I'm not able to pass variables to the $m object.

我试图在 Laravel 4 中使用邮件类,但我无法将变量传递给 $m 对象。

the $team object contains data I grabbed from the DB with eloquent.

$team 对象包含我雄辩地从数据库中抓取的数据。

Mail::send('emails.report', $data, function($m)
{
   $m->to($team->senior->email, $team->senior->first_name . ' '. $team->senior->last_name );
   $m->cc($team->junior->email, $team->junior->first_name . ' '. $team->junior->last_name );
   $m->subject('Monthly Report');
   $m->from('[email protected]', 'Sender');
});

For some reason I get an error where $team object is not available. I suppose it has something to do with the scope.

出于某种原因,我收到一个错误,其中 $team 对象不可用。我想这与范围有关。

Any ideas ?

有任何想法吗 ?

回答by Blessing

If you instantiated the $teamvariable outside of the function, then it's not in the functions scope. Use the usekeyword.

如果$team在函数外部实例化变量,则它不在函数范围内。使用use关键字。

$team = Team::find($id);
Mail::send('emails.report', $data, function($m) use ($team)
{
   $m->to($team->senior->email, $team->senior->first_name . ' '. $team->senior->last_name );
   $m->cc($team->junior->email, $team->junior->first_name . ' '. $team->junior->last_name );
   $m->subject('Monthly Report');
   $m->from('[email protected]', 'Sender');
});

Note: The function being used is a PHP Closure (anonymous function)It is not exclusive to Laravel.

注意:正在使用的函数是一个PHP 闭包(匿名函数),它不是 Laravel 独有的。