我需要在 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
,它会正确打印出每封电子邮件。
那么这里发生了什么?
最佳答案
您有anonymous function (又名闭包),其范围内没有 $email
。
Closures (anonymous functions) may also inherit variables from the parent scope. Any such variables must be passed to the
use
language construct.
您必须将 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!');
});
}
关于php - 发送邮件时 undefined variable $email - 即使该变量存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33036962/