Laravel 私有变量在 Controller 中的两个方法之间共享

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20692109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:46:51  来源:igfitidea点击:

Laravel private variable shared between two methods in Controller

phpmethodslaravellaravel-4share

提问by Sysrq147

How to use private variable in Laravel Controller, and share that variable value between two methods. (Set it in one use it in another).

如何在 Laravel Controller 中使用私有变量,并在两个方法之间共享该变量值。(将其设置在一个使用它在另一个)。

回答by Antonio Carlos Ribeiro

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();

And it will print newvalue.

它会打印newvalue.

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 变量中:

Session::put('variable', $newvalue);

and then

进而

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');

And in the second

而在第二

Session::get('variable');

回答by windmaomao