請求對象
介紹:對http請求參數的讀取,不管是post還是get,都是通過使用請求對象類Request來實現的。文件目錄(tp6:vendor\topthink\framework\src\think\Request.php)
注入方法:
1.通過構造函數注入
<?php namespace app\index\controller; use think\Request; class Index { /** * @var \think\Request Request實例 */ protected $request; /** * 構造方法 * @param Request $request Request對象 * @access public */ public function __construct(Request $request) { $this->request = $request; } public function index() { return $this->request->param('name'); } }
2.直接在方法中注入
<?php namespace app\index\controller; use think\Request; class Index { public function index(Request $request) { return $request->param('name'); } }
3.通過靜態方法調用
<?php namespace app\index\controller; use think\facade\Request; class Index { public function index() { return Request::param('name'); } }
4.助手函數
<?php namespace app\index\controller; class Index { public function index() { return request()->param('name'); } }
獲取請求傳參
萬能方法,可以獲取任何請求的參數(除了文件(file)之外);file需要使用file()方法獲取
request->param()
<?php namespace app\controller; use app\BaseController; use app\Request; class User extends BaseController { public function register(Request $req){ $req->param();//獲取所有參數,返回一個數組,里面是參數集合 $req->param("name");//獲取指定字段的參數 } }
指定請求類型獲取,只能獲取對應請求的參數
get 獲取 $_GET 變量 post 獲取 $_POST 變量 put 獲取 PUT 變量 delete 獲取 DELETE 變量 session 獲取 SESSION 變量 cookie 獲取 $_COOKIE 變量 request 獲取 $_REQUEST 變量 server 獲取 $_SERVER 變量 env 獲取 $_ENV 變量 route 獲取 路由(包括PATHINFO) 變量 middleware 獲取 中間件賦值/傳遞的變量 file 獲取 $_FILES 變量 //這個是比較常用的
獲取請求類型
request->method()//獲取當前請求類型
<?php namespace app\controller; use app\BaseController; use app\Request; class User extends BaseController { public function register(Request $req){ $requestType= $req->method();//永遠返回大寫字符串 var_dump($requestType); } }
獲取當前請求類型 method
判斷是否GET請求 isGet
判斷是否POST請求 isPost
判斷是否PUT請求 isPut
判斷是否DELETE請求 isDelete
判斷是否AJAX請求 isAjax
判斷是否PJAX請求 isPjax
判斷是否JSON請求 isJson
判斷是否手機訪問 isMobile
判斷是否HEAD請求 isHead
判斷是否PATCH請求 isPatch
判斷是否OPTIONS請求 isOptions
判斷是否為CLI執行 isCli
判斷是否為CGI模式 isCgi
獲取請求頭數據
request->header()
<?php namespace app\controller; use app\BaseController; use app\Request; class User extends BaseController { public function register(Request $req){ $heads= $req->header();//獲取全部請求頭 $heads= $req->header('content-type');//獲取指定請求頭值 var_dump($heads); } }
