如何在Laravel Controller中使用私有变量,并在两个方法之间共享该变量值.(将其设置为一个用于另一个).
你说的是一个控制器,对吧?所以我会假设这是你的意思:
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变量中:
Session::put('variable', $newvalue);
然后
Session::get('variable');
或者,您可以使用返回方法所需的值重定向:
Redirect::to('posts')->with('variable','this is a new value');
在第二个
Session::get('variable');