问题描述
如何在 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 中的两个方法之间共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)