Laravel private variable shared between two methods in Controller

喜你入骨 提交于 2019-11-28 01:26:42

问题


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


回答1:


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.

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

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



回答2:


You can also use Setting approach outlined here

laravel share variable across all methods in a controller

and

Laravel: Passing default variables to view

and you can download Setting here, https://github.com/Phil-F/Setting



来源:https://stackoverflow.com/questions/20692109/laravel-private-variable-shared-between-two-methods-in-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!