Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

php - Laravel private variable shared between two methods in 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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...