[英]Undefined variable in foreach loop
当我执行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;
}
你错过了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!');
});
}
请参阅此文档 - 尤其是第三个示例。 引用:
闭包还可以从父作用域继承变量。 必须在函数头中声明任何此类变量。
这是因为你在函数范围内。
假设你在这里使用PEAR包,我不明白你为什么要传递一个函数: http : //pear.php.net/manual/en/package.mail.mail.send.php
如果您打算这样做,可以使用use
关键字将变量传递到函数范围:
function($m) use($recipient) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.