四种方法从控制器中调用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
运行结果均为下图:

代码分别如下:
<?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());
}
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号