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

Sys*_*147 4 php methods share laravel laravel-4

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

Ant*_*iro 9

你说的是一个控制器,对吧?所以我会假设这是你的意思:

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

}
Run Code Online (Sandbox Code Playgroud)

如果你在同一个请求中做事,你可以

$this->method1('newvalue');

echo $this->method2();
Run Code Online (Sandbox Code Playgroud)

它会打印出来newvalue.

如果您在请求之间执行此操作,则需要记住您的应用程序在请求重新启动新应用程序后结束,因此您需要将其存储在某个位置,例如在Session变量中:

Session::put('variable', $newvalue);
Run Code Online (Sandbox Code Playgroud)

然后

Session::get('variable');
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用返回方法所需的值重定向:

Redirect::to('posts')->with('variable','this is a new value');
Run Code Online (Sandbox Code Playgroud)

在第二个

Session::get('variable');
Run Code Online (Sandbox Code Playgroud)