簡體   English   中英

Codeigniter 如果 URL 段丟失

[英]Codeigniter if URL segment is missing

發現第三個 URL 段可以直接傳遞給函數的參數后,我做了以下操作。

URL 示例:

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

Function 在profile controller:

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

使用$this->uri->segment(3)返回 FALSE 是不存在段。 使用 function 參數我得到

缺少參數 1

如果缺少第 3 個 URL 段,我如何返回 FALSE 而不執行 function? 如果可能的話,我正在尋找一個沒有 if 語句的簡單解決方案。

您得到“缺少參數 1”,因為 function 沒有得到參數。

嘗試

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

默認 arguments 怎么樣:

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

你也可以使用這個:

 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
}
if ($this->uri->segment(3)) {
  return true
} else {
  return false
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM