Laravel-控制器功能之间共享变量

时间:2018-12-01 19:12:03

标签: php laravel controller

我是Laravel的新手,正在从事一个简单的项目,在我的控制器(TestController)中,我有两个功能(过程和显示)

我想做的是在函数之间传递 $ email 变量,这样我就可以在show函数中使用它,但是我不知道该怎么做。

控制器

class TestController extends Controller
{    

    public function process(Request $request){
        if($request->ajax()) {
            $email = $request->get( "fullemail" );
        }
    }


    public function show(){

    }

}

任何帮助将不胜感激。在此先感谢:)


编辑

我按照以下步骤编辑了代码。目前,我收到Too few arguments to function App\Http\Controllers\TestController::show(), 0 passed and exactly 1 expected错误。

控制器

class TestController extends Controller
{    
    public function process(Request $request){
        if($request->ajax()) {
            $email = $request->get( "fullemail" );
            $this->show($email);
        }
    }

    public function show($email){
        dd($email)
    }
}

1 个答案:

答案 0 :(得分:0)

如果您已经接触过laravel并且知道什么功能,那么您可能已经知道该怎么做:

class TestController extends Controller
{    

    public function process(Request $request){
        if($request->ajax()) {
            $email = $request->get( "fullemail" );
            $this->show($email);
        }
    }


    public function show($email){
        // Do whatever you will with the $email variable.
        return view('some.view', ['email' => $email]);
    }

}

另一种方法:

class TestController extends Controller
{    

    // Declare this variable as a class property - protected means, that only this class and any class that inherits from this class can access the variable.
    protected $email;

    public function process(Request $request){
        if($request->ajax()) {
            $this->email = $request->get( "fullemail" );
            $this->show();
        }
    }


    public function show() {
        // Do whatever you will with the $email variable.
        return view('some.view', ['email' => $this->email]);
        // On top of that, if you change $email value here, the changes will be available in all other methods as well.
        // $this->email = strtolower($this->email);
    }

}