foreach循环中的未定义变量

时间:2013-03-25 00:37:48

标签: php

当我执行foreach()循环时,当前数组元素的值$recipient未在行->to($recipient)上定义。这是为什么?

PHP代码(抛出错误)

foreach($recipients as $recipient) {
    Mail::send('emails.invite', $data, function($m){
        $m
            ->from('welcome@website.com', Auth::user()->name)
            ->to($recipient)
            ->subject('Auth::user()->name has invited you!');
    });
}

错误

Notice: Undefined variable: recipient

PHP代码(无错误)

foreach($recipients as $recipient) {
    echo $recipient;
}

2 个答案:

答案 0 :(得分:3)

您错过了use关键字。将代码更改为:

foreach($recipients as $recipient) {
    Mail::send('emails.shareListing', $data, function($m) use($recipient) {
        $m
            ->from('share@asd.com', Auth::user()->name)
            ->to($recipient)
            ->subject('Auth::user()->name has shared a listing with you!');
    });
}

this documentation - 尤其是第三个例子。引用:

  

闭包还可以从父作用域继承变量。必须在函数头中声明任何此类变量。

答案 1 :(得分:1)

这是因为你在函数的范围内。

假设你在这里使用PEAR包,我不明白你为什么要传递一个函数:http://pear.php.net/manual/en/package.mail.mail.send.php

如果您打算这样做,可以使用use关键字将变量传递到函数范围:

function($m) use($recipient) {