Laravel 私有变量在 Controller 中的两个方法之间共享
如何在 Laravel Controller 中使用私有变量,并在两个方法之间共享该变量值.(设置在一个使用它在另一个).
How to use private variable in Laravel Controller, and share that variable value between two methods. (Set it in one use it in another).
推荐答案
您说的是单个控制器,对吗?所以我假设这就是你的意思:
You're talking about one single controller, right? So I'll assume that this what you mean:
class ControllerController extends Controller {
private $variable;
public function __construct($whatever)
{
$this->variable = $whatever;
}
public function method1($newValue)
{
$this->variable = $newValue;
}
public function method2()
{
return $this->variable;
}
}
如果你在同一个请求中做事情,你可以
If you are doing thing in the same request, you can
$this->method1('newvalue');
echo $this->method2();
它会打印newvalue
.
如果您在请求之间执行此操作,您需要记住您的应用程序在请求重新启动后结束,因此您需要将其存储在某处,例如在 Session 变量中:
If you are doing it between requests, you need to remember that your application ends after a request a restart in a new one, so you'll need to store it somewhere, like in a Session variable:
Session::put('variable', $newvalue);
然后
Session::get('variable');
或者您可以使用返回方法所需的值进行重定向:
Or you can redirect with the value you need to get back in your method:
Redirect::to('posts')->with('variable','this is a new value');
然后在第二个
Session::get('variable');
相关文章