thinkPHP 参数传入

通过操作方法的参数绑定功能,可以实现自动获取URL的参数,仍然以上面的控制器为例,控制器代码如下:

<?php

namespace app\index\controller;

class Index
{
    public function index()
    {
        return 'index';
    }

    public function hello($name = 'World')
    {
        return 'Hello,' . $name . '!';
    }
}

当我们访问

http://tp5.com/index.php/index/index/hello

就是访问app\index\controller\Index控制器类的hello方法,因为没有传入任何参数,name参数就使用默认值World。如果传入name参数,则使用:

http://tp5.com/index.php/index/index/hello/name/thinkphp

页面输出结果为:

Hello,thinkphp!

现在给hello方法增加第二个参数:

    public function hello($name = 'World', $city = '')
    {
        return 'Hello,' . $name . '! You come from ' . $city . '.';
    }

访问地址为

http://tp5.com/index.php/index/index/hello/name/thinkphp/city/shanghai

页面输出结果为:

Hello,thinkphp! You come from shanghai.

可以看到,hello方法会自动获取URL地址中的同名参数值作为方法的参数值,而且这个参数的传入顺序不受URL参数顺序的影响,例如下面的URL地址输出的结果和上面是一样的:

http://tp5.com/index.php/index/index/hello/city/shanghai/name/thinkphp

或者使用

http://tp5.com/index.php/index/index/hello?city=shanghai&name=thinkphp

还可以进一步对URL地址做简化,前提就是我们必须明确参数的顺序代表的变量,我们更改下URL参数的获取方式,把应用配置文件中的url_param_type参数的值修改如下:

// 按照参数顺序获取
'url_param_type' => 1,

现在,URL的参数传值方式就变成了严格按照操作方法的变量定义顺序来传值了,也就是说我们必须使用下面的URL地址访问才能正确传入namecity参数到hello方法:

http://tp5.com/index.php/index/index/hello/thinkphp/shanghai

页面输出结果为:

Hello,thinkphp! You come from shanghai.

如果改变参数顺序为

http://tp5.com/index.php/index/index/hello/shanghai/thinkphp

页面输出结果为:

Hello,shanghai! You come from thinkphp.

显然不是我们预期的结果。

同样,我们试图通过

http://tp5.com/index.php/index/index/hello/name/thinkphp/city/shanghai

访问也不会得到正确的结果。

注意


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

 

 

 

 

posted @ 2019-06-05 09:01  聽丶  阅读(648)  评论(0编辑  收藏  举报