如何在 Laravel Controller 中使用私有(private)变量,并在两个方法之间共享该变量值。 (在一个中设置它在另一个中使用它)。
最佳答案
您是在谈论一个 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');
关于php - Laravel 私有(private)变量在 Controller 中的两个方法之间共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20692109/