2011-07-18 56 views
3

發現第三個URL段可以直接傳遞給函數的參數我做了以下操作。如果URL段丟失Codeigniter

URL例如:

http://www.mysite.com/profile/user/64

功能在profile控制器:

function user($user_id) //$user_id is 3rd URL segment 
{ 
    //get data for user with id = $user_id 
} 

使用$this->uri->segment(3)返回FALSE是沒有段存在。隨着功能參數我得到

缺少參數1

我怎樣才能返回FALSE,如果第三URL段缺失不執行的功能?如果可能,我正在尋找一個沒有if語句的簡單解決方案。

+0

嘗試'$這個 - > URI->段(2)'。我沒有使用CodeIgniter,但我猜測URI段索引從0開始。 – 2011-07-18 18:28:31

+0

@wtp - CI段在索引之後開始,或者如果在域之後使用htaccess刪除索引(假設CI索引位於domian的根中)並啓動在這個例子中,從1開始計數3是正確的。 FYI – BrandonS

+0

@BrandonS好吧,我的壞。 :) – 2011-07-18 18:42:48

回答

3

什麼默認參數:

function user($user_id = FALSE) //$user_id is 3rd URL segment 
{ 
    //get data for user with id = $user_id 
} 
+0

謝謝!所以這應該返回FALSE執行查詢之前?使用codeigniter,第三段實際上是user_id – CyberJunkie

+0

你說得對。我正在想別的東西。 – cwallenpoole

+1

如果user_id沒有定義,那麼它將默認爲FALSE。如果它被定義,它將是該值。 – cwallenpoole

4

你得到「缺少參數1」,因爲功能沒有得到說法。

嘗試

function user(){ 
    if($this->uri->segment(3)){ 
     //get data for user with id = $this->uri->segment(3) 
    } 
} 
2

你也可以使用此:

public function user($id = null) 
{ 
    if(!isset($id)) 
    exit(); 

    // get data for user with id = $id 
} 

或本

public function user() 
{ 
    if(! $this->uri->segment(3)) 
    exit(); 

    // get data for user with id = $id 
}