代码之家  ›  专栏  ›  技术社区  ›  mercury

Laravel和匿名函数参数流

  •  0
  • mercury  · 技术社区  · 9 年前

    在Laravel 5中,我无法理解像这样的函数(匿名函数)内部和外部参数的移动

    Route::get('user/{id}', function ($id) {
        return 'User '.$id;
    });
    

    参数如何从..我真的需要知道$id如何转到Route::get函数..语法对我来说很难在没有copy n paste的情况下编写。

    1 回复  |  直到 9 年前
        1
  •  2
  •   Anonymous    9 年前

    争论不会神奇地“移动”。当您执行此操作时,laravel将获取路径/函数组合,并将其存储以备以后使用。这是所发生情况的简化版本:

    class Route
    {
         private static $GET = array();
    
         public static function get($path, $callback)
         {
             self::$GET[] = array($path, $callback);
         }
    }
    

    然后,在添加了所有路由之后,它检查调用网页的URL,并找到与之匹配的路径。有一些内部程序需要 $path 并将其转换为正则表达式,如 #user/(?P<id>.+)# ,所以匹配只是通过以下方式完成的 preg_match() 。成功命中后,它停止并提取变量:

    '/user/foobar' has the username extracted: array('id' => 'foobar')
    

    然后使用 reflection 以将回调中的参数与URL中的数据匹配。

    $callback_reflection = new ReflectionFunction($callback);
    $arguments = $callback_reflection->getParameters();
    /* some algorithm to match the data and store in $args */
    $result = $callback_reflection->invokeArgs($args);
    

    这个 invokeArgs() 方法是使用正确的参数执行回调的方法。这里没有太多魔法。请参见 Router class 了解更多详情。