問題描述
如何在 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 中的兩個方法之間共享的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!