我正在编写这个简单的代码来发送带有附件的邮件,但是,我无法将路径传递到文件变量。
$pathToFile = "Sale-".$id.".csv";
Mail::send(array('html' => 'sales.invoice_template'), $data, function($message)
{
$message->to('test@test.com'); // dummy email
$message->attach($pathToFile);
});
上面的代码抛出:
Undefined variable: pathToFile
此外,我尝试将一个变量(在上面的闭包中添加了$pathToVariable和$message)传递到闭包,但它抛出了以下错误:
Missing argument 2 for SaleController::{closure}()
它基本上不会识别闭包之外的任何变量。有人能帮我吗?
你可以试试这个:
$pathToFile = "Sale-".$id.".csv";
Mail::send(array('html' => 'sales.invoice_template'), $data, function($message) use ($pathToFile)
{
$message->to('test@test.com'); // dummy email
$message->attach($pathToFile);
});
说明:
使用($pathToFile)
允许您在闭包中使用变量。
当在闭包中引用$pathToFile时,脚本正在寻找要在闭包中声明的$pathToFile。由于不存在声明,您会看到未定义的变量错误。
默认情况下,函数内部使用的任何变量都仅限于本地函数范围。
来源:http://www.php.net/manual/en/language.variables.scope.php
要修复它,您应该能够将$pathToFile传递到您的闭包中,例如:
Mail::send(array('html' => 'sales.invoice_template'), $data, function($message, $pathToFile)
{
$message->to('test@test.com'); // dummy email
$message->attach($pathToFile);
});