1

当我执行foreach()循环时,当前数组元素的值$recipient未定义在 line 上->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;
}
4

2 回答 2

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!');
    });
}

请参阅本文档- 特别是第三个示例。引用:

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

于 2013-03-25T00:39:53.073 回答
1

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

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

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

function($m) use($recipient) {
于 2013-03-25T00:41:01.400 回答