php - 发送邮件时 undefined variable $email - 即使该变量存在?

标签 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,它会正确打印出每封电子邮件。

那么这里发生了什么?

最佳答案

您有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/

相关文章:

php - Laravel DB::raw 使用 SELECT 列 AS "Example Name"

laravel - 如何正确复制正在运行的 Laravel 4 项目

php - 优化查询——急切加载占用太多内存

php - 加载 mysqli 扩展时为 "version libmysqlclient_18 not defined in file libmysqlclient.so.18"

javascript - 如何让window.location.href执行POST请求

apache - 为什么 laravel homestead 不运行 Apache

php - url 重定向到根文件夹后的 Laravel 斜线

mysql - 使用 ON DUPLICATE KEY UPDATE 的 Laravael4 db 原始查询会删除错误

php - 在 curl php 中获取最后一个重定向的 url

PHP shell_exec() - 不打印动态输出,仅打印静态回显文本