在php中编写回调函数时传递参数(Laravel 5) [英] Passing parameters when writing a callback function in php (Laravel 5)
本文介绍了在php中编写回调函数时传递参数(Laravel 5)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Laravel 5在php中编程.我有这段代码.
I'm programming in php using Laravel 5. I have this code.
$newUser = $this->create($request->all());
$newUser->save();
$newAccount = new Account(['user_id' => $newUser->getAttribute('id')]);
$newAccount->save();
Mail::send('emails.welcome', ['username' => $newUser->name, 'active_token' => $newUser->active_token], function($message)
{
$message->to($newUser->email, $newUser->name)->subject('Welcome');
});
这里的问题是我不知道如何在回调函数中传递"newUser"变量.由于范围原因,它不起作用.那么,在编写回调函数时如何传递参数?为了在那个范围内使用它们?
The problem here is that I don't know how to pass the "newUser" variable within the callback function. It is not working because of the scope. So, how can I pass parameters when writing a callback function? in order to use them inside that scope?
谢谢
推荐答案
使用php匿名函数,您可以使用 use($ variable)
包含来自父作用域的变量:
With php anonymous functions you can include variables from the parent scope with use($variable)
:
Mail::send(
'emails.welcome',
['username' => $newUser->name, 'active_token' => $newUser->active_token],
function($message) use($newUser)
{
$message->to($newUser->email, $newUser->name)->subject('Welcome');
});
http://php.net/manual/en/functions.onymous.php#example-195
这篇关于在php中编写回调函数时传递参数(Laravel 5)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文