[英]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.