Slim 3 重定向路由循环不起作用

Slim 3 redirect route loop not working

我正在尝试创建一个简单的路由,以根据 array/key.

将端点重定向到特定的 URL
$redirects = [
    "/ios" => $GLOBALS['config']['iosAppStoreLink'],
    "/android" => $GLOBALS['config']['androidAppStoreLink']
];

/**
 * Redirects
 */
foreach($redirects as $endpoint => $url) {
    $app->get($endpoint, function($request, $response) {
        return $response->withRedirect($url);
    });
}

一旦我进入 $app->get 函数,端点就可以毫无问题地创建,它不允许我使用 $url... 我收到 Undefined Index 错误在我的控制台中。

我做错了什么,为什么我无法访问 $url 变量?

要允许函数从其自身范围之外访问 $url,您可以使用 function() use() { 语法...

foreach($redirects as $endpoint => $url) {
    $app->get($endpoint, function($request, $response) use ($url) {
        return $response->withRedirect($url);
    });
}