dongyi2159 2010-03-11 05:37
浏览 47
已采纳

如何在PHP中动态传递参数?

I need to pass the $route to its inner function,but failed:

function compilePath( $route )
{
    preg_replace( '$:([a-z]+)$i', 'pathOption' , $route['path'] );
    function pathOption($matches)
    {
        global $route;//fail to get the $route
    }
}

I'm using php5.3,is there some feature that can help?

  • 写回答

2条回答 默认 最新

  • douduan5753 2010-03-11 05:40
    关注

    I don't think you can do anything like that in PHP 5.2, unfortunatly -- but as you are using PHP 5.3... you could use Closures to get that to work.


    To begin, here's a quick example of using a Closure :

    function foo()
    {
        $l = "xyz";
        $bar = function () use ($l)
        {
            var_dump($l);
        };
        $bar();
    }
    foo();
    

    Will display :

    string 'xyz' (length=3)
    

    Notice the use keyword ;-)


    And here's an example of how you could use that in your specific case :

    function compilePath( $route )
    {
        preg_replace_callback( '$:([a-z]+)$i', function ($matches) use ($route) {
            var_dump($matches, $route);
        } , $route['path'] );
    }
    
    $data = array('path' => 'test:blah');
    compilePath($data);
    

    And you'd get this output :

    array
      0 => string ':blah' (length=5)
      1 => string 'blah' (length=4)
    
    array
      'path' => string 'test:blah' (length=9)
    

    A couple of notes :

    • I used preg_replace_callback, and not preg_replace -- as I want some callback function to be called.
    • I'm using an anonymous function as callback
    • And that anonymous function is importing $route, with the new use keyword.
      • Which means that, in my callback function, I can access both the matches, which are always passed by preg_replace_callback to the callback function, and the $route.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 vscode问题请教
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM