如何在Laravel控制器中使用私有变量,并在两个方法之间共享该变量的值(在一个方法中设置,在另一个方法中使用)。
你说的是一个单一的控制器,对吗?那么我会假设这是你的意思:
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;
}
}
如果您在同一请求中进行操作,您可以
$this->method1('newvalue');
echo $this->method2();
它将打印newvalue
。
如果您在请求之间执行此操作,则需要记住,应用程序在请求结束后会重新启动一个新的应用程序,因此您需要将其存储在某个地方,例如会话变量中:
Session::put('variable', $newvalue);
然后
Session::get('variable');
或者你可以使用需要在方法中返回的值来进行重定向:
Redirect::to('posts')->with('variable','this is a new value');
其次,在第二个
Session::get('variable');