发送邮件时未定义的变量$ email - 即使该变量存在?

时间:2015-10-09 11:20:24

标签: php laravel laravel-4

我需要在Laravel 4.2中发送消息的电子邮件数组。这个数组是

$email_arr = ["me@yahoo.com","friend@gmail.com"]

现在我的逻辑是简单地遍历电子邮件阵列并向每个人发送消息,如下所示:

foreach($email_arr as $email){
            Mail::send('emails.invite', array('pool_code' => 'test'), function($message) {
                $message->to($email)->subject('Join my capture pool!');
            });
        }

但是,我收到错误,指向$message->to($email)->subject('Join my capture pool!');,其中显示Undefined variable: email

我觉得这很奇怪,因为变量显然存在,如果我在循环中echo $email,它会正确地打印出每封电子邮件。

那么这里发生了什么?

1 个答案:

答案 0 :(得分:12)

你有anonymous function(a.k.a关闭),其范围内没有$email

  

闭包(匿名函数)也可以从父作用域继承变量。任何此类变量都必须传递给use语言构造。

您必须将use添加到此功能。

foreach($email_arr as $email){
    Mail::send('emails.invite', array('pool_code' => 'test'), function($message) use($email) {
        $message->to($email)->subject('Join my capture pool!');
    });
}