在控制器中
class acontroller extends Controller
{
private $variable;
public function __construct(){
$this->variable;
}
public function first(){
$calculation = 1 + 1;
$this->variable = $calculation;
return view('something.view');
}
public function second(){
dd($this->variable);
return view('something.view2');
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个例子。我想做的是将第一个方法中的计算结果传递给第二个方法。我期望在 dd() 内的第二个方法中显示结果 2,但我得到的是 null。
出了什么问题以及如何解决这个问题?
你真的应该重新设计它。您可以做的是创建第三种方法并在其中进行计算。然后只需从第一个和第二个方法中调用此方法即可。
public function first(){
$this->third();
dd($this->variable);
return view('something.view');
}
public function second(){
$this->third();
dd($this->variable);
return view('something.view2');
}
public function third(){
$calculation = 1 + 1;
$this->variable = $calculation;
}
Run Code Online (Sandbox Code Playgroud)
只需在方法$this->second();后面插入即可。$this->variable = $calculation;first