doxp30826 2018-06-09 06:53 采纳率: 0%
浏览 40
已采纳

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

I'm trying to make a simple route to redirect endpoints to a specific URL based on an array/key.

$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);
    });
}

The endpoints get created without issue just once I'm inside of the $app->get function, it will not allow me to use $url... I get an Undefined Index error in my console.

What am I doing wrong here, why am I not able to access the $url variable?

  • 写回答

1条回答 默认 最新

  • doumeng3345 2018-06-09 07:06
    关注

    To allow the function to access the $url from outside of it's own scope, you could use function() use() { syntax...

    foreach($redirects as $endpoint => $url) {
        $app->get($endpoint, function($request, $response) use ($url) {
            return $response->withRedirect($url);
        });
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题