[英]how to solve undefined variable error in compact() function?
I want to send email with some information. 我想发送一些信息的电子邮件。 That's why I use
compact()
function within view()
function. 这就是为什么我在
view()
函数中使用compact()
view()
函数。 But I got an error 'undefined variable': 但是我得到了一个错误“未定义的变量”:
public $message_to_send="";
public $first_name_to_send="";
public function __construct($first_name,$message) {
$this->message_to_send=$message;
$this->first_name_to_send=$first_name;
}
public function build(){
return $this->view('email/contactmessageemail',compact('message_to_send','first_name_to_send'));
}
The error message is: 错误消息是:
compact(): Undefined variable: message_to_send
compact():未定义的变量:message_to_send
try to edit it to 尝试将其编辑为
view('email.contactmessageemail',[
'message_to_send' => $this->message_to_send,
'first_name_to_send' => $this->first_name_to_send
]);
compact
didn't work in your case because the variables that you want to pass in is not locally defined in the method scope it is declared as a public property compact
在您的情况下不起作用,因为您要传递的变量未在方法范围内本地定义,因此将其声明为公共属性
This was a breaking changed introduced in PHP 7.3 with compact()
. 这是PHP 7.3中带有
compact()
的重大更改。 Previously, you could send through undefined variables with compact()
, but now it flags as an error. 以前,您可以使用
compact()
发送未定义的变量,但现在将其标记为错误。
compact()
is still a fantastic method - but you will need to define the variables within the method that you are using it. compact()
仍然是一种出色的方法-但是您将需要在使用它的方法中定义变量。 To keep code clean and readable, I suggest you define the variables and then pass using compact()
as you had originally intended. 为了保持代码的清洁和可读性,建议您定义变量,然后按原先的意图使用
compact()
传递。
So you can fix using the original code like this: 因此,您可以使用以下原始代码进行修复:
public function build(){
$message_to_send = $this->message_to_send;
$first_name_to_send = $this->first_name_to_send;
return view('email.contactmessageemail',compact('message_to_send','first_name_to_send'));
}
Note I removed $this
from the view call. 注意我从视图调用中删除了
$this
。
You can also always pass the variables right into the build()
method - which is sort of the norm - then you don't have to define within the method. 您还可以始终将变量直接传递到
build()
方法中(这是一种规范),那么您不必在方法中进行定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.