tp5参数绑定

关闭路由后的普通模式任然能够经过操做方法的参数绑定、控制器和空操做等特性实现url地址的简化php

参数绑定(默认是按名称成对解析,):thinkphp

namespace app\index\Controller;

class Blog 
{
    public function read($id)
    {
        return 'id='.$id;
    }

    public function archive($year='2016',$month='01')
    {
        return 'year='.$year.'&month='.$month;
    }
}

//上例对应的URL访问地址分别是架构

http://serverName/index.php/index/blog/read/id/5app

http://serverName/index.php/index/blog/archive/year/2016/month/06函数

 
 

输出结果:
id=5
year=2016&month=06post

 

按照顺序解析变量须要修改配置文件的url_param_type参数this

// 按照顺序解析变量
'url_param_type'    =>  1,

上面的例子修改下访问url地址url

//修改url中year和month参数值的顺序
http://serverName/index.php/index/blog/archive/06/2016

输出结果:
year=06&month=2016

按顺序绑定参数,操做方法的参数只能使用URL pathinfo变量,而不能使用get或者post变量spa

参数绑定有一个特例,操做方法中定义有Request对象做为参数,不管参数位置在哪里,都会自动注入,而不须要进行参数绑定code

namespace app\index\Controller;
use think\Request

class Blog 
{
    public function demo1()
    {
        $year=Request:instance()->param('year');
        $month=Request:instance()->param('month');
        $all=Request:instance()->param();//获取所有参数变量
        $get=Request:instance()->get();//获取url?后的参数变量(获取到year变量2018)
        $rt=Request:instance()->route();//获取路径后面的参数变量(只获取到id变量123)
        $post=Request:instance()->post();//获取post参数变量(只获取到age变量18)

    }

    public function demo2(){
        //input获取url变量   同tp3的I()
           $id=input('get.id')
       
    }

    public function demo3(Request $request){
          //依赖注入
           $all=$request->param();
       
    }
}

http://localhost/demo1/123?year=2018(month变量为post传递)

 

架构方法(构造方法)参数绑定(V5.0.1)

当前请求的路由变量能够自动绑定到析构函数的参数,

namespace app\index\Controller;

class Blog 
{
    protected $name;
    public function __construct($name = null)
    {
        $this->name = $name;
    }
}
//若是访问http://localhost/index/index/index/name/thinkphp
//当前请求路由变量name,则thinkphp会自动传入析构方法里的name变量
相关文章
相关标签/搜索