zoukankan      html  css  js  c++  java
  • thinkPHP 参数传入

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

    <?php
    
    namespace appindexcontroller;
    
    class Index
    {
        public function index()
        {
            return 'index';
        }
    
        public function hello($name = 'World')
        {
            return 'Hello,' . $name . '!';
        }
    }
    

    当我们访问

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

    就是访问appindexcontrollerIndex控制器类的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变量。

     
     
  • 相关阅读:
    函数传参-修改文本
    函数传参-商品计价
    嵌套选项卡自动播放
    仿淘宝自动播放菜单栏
    仿淘宝侧边栏菜单
    图片自动切换
    定时器应用-页面弹出广告
    转:Java面试题集(1-50)
    转:115个Java面试题和答案——终极列表(上)
    毕向东day01笔记--dos-jdk-jre-环境变量等
  • 原文地址:https://www.cnblogs.com/xu1115/p/10977611.html
Copyright © 2011-2022 走看看