2016-11-18 63 views
-1

自定義路線不正確,總是路線工作user.htm自定義路由工作不正常[F3]

的index.php

$routes = [ 
    "/" => "index.htm", 
    "/user/[email protected]" => "user.htm","/user/@id" => "user.htm", 
]; 

foreach ($routes as $path => $file) { 
    $f3->route("GET ".$path, 
    function($f3){ 
     global $file,$path; 
     echo View::instance()->render($file); 
    } 
); 
} 

回答

1

試試這個:

$routes = [ 
    "/" => "index.htm", 
    "/user/[email protected]" => "user.htm", 
    "/user/@id" => "user.htm", 
]; 

foreach ($routes as $path => $file) 
{ 
    $f3->route("GET " . $path, 
    function ($f3) use ($file) 
    { 
     echo View::instance()->render($file); 
    } 
); 
} 
+1

工作,謝謝。但是,請您詳細說明爲什麼這種方法有效,而且我使用的方法不適用?再次感謝:D –

1

Bryan Velastegui的答案是正確的。但在這裏就是爲什麼你的代碼沒有工作:

  1. $f3->route()每個路由URI的功能(稱爲「路由處理程序」),映射而不執行它
  2. foreach循環將下列值連續存儲到$file變量中:index.html,user.htmuser.htm(再次)。因此,在循環結束時,$file保存爲user.htm
  3. 一旦您調用$f3->run(),框架將執行匹配當前路由的路由處理程序,該路由處理程序本身引用全局變量$file,持有user.htm

通常,您不應該使用global關鍵字。這隻會造成意想不到的問題,就像你遇到的問題一樣。而且這對代碼可維護性沒有幫助。

我建議您閱讀關於use keyword的文檔,以瞭解Bryan Velastegui的代碼是如何工作的。

+0

謝謝朋友,我真的很新,沒有很好的解釋。 – shinigamicorei7