laravel 5.2控制器中的全局变量


Global variables in laravel 5.2 controllers

我希望其他控制器方法共享一个变量。这个变量可以通过一种控制器方法更新,而这种变化应该反映在其他方法中?有什么建议吗?最好的做法是什么?这是我的代码:

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

  }

在构造函数中设置变量。

function _construct() { $this->global = "some value";} 

所以,你不仅想要一个全局变量,你还希望这个变量也应该被其他路径更改。实现这一点的一种方法是使用会话。

function a() {
    session()->put('global_variable', 'set by method a');
    //your other logic
}

以及从方法b…

function b() {
    //get the variable set by method a here
    dd(session()->get('global_variable'));
}

您可以在config中创建一个新文件并使用

config('your_new_file_name.key')

检查此项:https://laracasts.com/discuss/channels/general-discussion/laravel-5-global-variables