我想要一个变量由其他控制器方法共享.这个变量可以通过一种控制器方法更新,并且变化应该反映在其他方法中?有什么建议 ?这样做的最佳做法是什么?这是我的代码:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Session;
class test extends Controller
{
public $global;
public function __construct()
public function a(Request $request){
$this->global="some value"
}
public function b(Request $request){
echo $this->global;
//it always return a null
}
}
Run Code Online (Sandbox Code Playgroud)
在构造函数中设置变量.
function _construct() { $this->global = "some value";}
Run Code Online (Sandbox Code Playgroud)
因此,您不仅需要全局变量,还希望此变量也应该由其他路径更改.实现此目的的一种方法是使用会话.
function a() {
session()->put('global_variable', 'set by method a');
//your other logic
}
Run Code Online (Sandbox Code Playgroud)
从方法b ......
function b() {
//get the variable set by method a here
dd(session()->get('global_variable'));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7550 次 |
| 最近记录: |