【问题标题】:Undefined variable $email when sending mail - even though the variable exists?发送邮件时未定义变量 $email - 即使该变量存在?
【发布时间】:2015-10-09 19:31:11
【问题描述】:

我有一系列电子邮件需要在 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 它会正确打印出每封电子邮件。

那么这里发生了什么?

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    您有 anonymous function(也称为闭包),它的范围内没有 $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!');
        });
    }
    

    【讨论】:

    • 是的,就是这样。谢谢。将在 10 分钟内接受答案。
    猜你喜欢
    • 1970-01-01
    • 2015-01-21
    • 2014-12-01
    • 2020-11-04
    • 2022-11-04
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    相关资源
    最近更新 更多