foreach循环中的未定义变量
问题描述:
当我执行foreach()
循环时,当前数组元素的值$recipient
未在行->to($recipient)
上定义。为什么是这样?foreach循环中的未定义变量
PHP代码(抛出错误)
foreach($recipients as $recipient) {
Mail::send('emails.invite', $data, function($m){
$m
->from('[email protected]', 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('[email protected]', Auth::user()->name)
->to($recipient)
->subject('Auth::user()->name has shared a listing with you!');
});
}
见this documentation - 尤其是第三个例子。报价:
闭包也可能继承父范围的变量。任何这样的变量都必须在函数头部声明。
答
这是因为你在功能范围内。
假设你在这里使用PEAR包,我不明白为什么你传递一个功能都:http://pear.php.net/manual/en/package.mail.mail.send.php
如果您打算做这个,你可以使用关键字use
传递变量进入功能范围:
function($m) use($recipient) {
作品,谢谢!! – Nyxynyx 2013-03-25 00:42:38
欢迎您!曾经有过这个问题。 PHP文档对此没有太多的说明。 – hek2mgl 2013-03-25 00:45:53