Laravel private variable shared between two methods in Controller(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');
这篇关于Laravel 私有变量在 Controller 中的两个方法之间共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel 私有变量在 Controller 中的两个方法之间共享


- 正确分离 PHP 中的逻辑/样式 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- Laravel 仓库 2022-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01