Laravel私有变量在Controller中的两个方法之间共享 [英] Laravel private variable shared between two methods in Controller

查看:235
本文介绍了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中的两个方法之间共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆