博客列表 >从控制器中调用Request类的四种方法

从控制器中调用Request类的四种方法

LIWEN的博客
LIWEN的博客原创
2018年01月20日 09:26:241706浏览

四种方法从控制器中调用Request类:
* 1、传统的new Request
* 2、静态代理:think\facade\Request
* 3、依赖注入:Request $request
* 4、直接调用父类Controller中的属性:$request : $this->request

类名:Demo1

位置:application/index/controller/Demo1.php

URL:http://www.tp5.com/index.php/index/Demo1/test4?name=peter&sex=male

运行结果均为下图:

2018-01-20_091550.png

代码分别如下:

<?php
namespace app\index\controller;
use think\Request;
use think\Controller;
class Demo1 extends Controller   //方法1和4中用到extends Controller,use think\Request;use think\Controller;
{
    //方法一:传统的new Request方法
    public function test1()
    {
        $request = new Request();
        dump($request->get());
    }
}
<?php
namespace app\index\controller;
use think\facade\Request;  //导入请求对象的静态代理,用于方法二
class Demo1
{
   //方法二:静态代理:think\facade\Request
    public function test2()
    {
        dump(Request::get());
    }
}
<?php
namespace app\index\controller;
class Demo1
{
    //方法三:依赖注入:Request $request
    public function test3(\think\Request $request)
    {
        dump($request->get());
    }
}
<?php
namespace app\index\controller;
use think\Request;  //导入think命名空间的Request类
use think\Controller;  //导入think命名空间的Controller类
class Demo1 extends Controller   //继承Controller类
{
    //方法四:直接调用父类Controller中的属性:$request : $this->request
    public function test4()
{
    dump($this->request->get());
}
}


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议