2012-07-08 71 views
2

我有一個用戶註冊腳本。在一個階段,我會調用三次方法。一旦檢查該方法是否返回true,否則如果沒有,它是否會返回一個字符串(包含錯誤消息),以及是否獲取返回的字符串並將其放入一個變量中。多次調用一個方法,是否有更高效的方法呢?

這樣做是否更有效率,這樣我只需要調用一次該方法?但仍然得到我需要的所有答案?

繼承人的代碼:

//check thumbnail is present and good 
      if($register->checkThumb()){ 
       //send image to permanent image directory 
       $register->moveUploadedImage(); 

       //if the thumbnail failed validation put the error message in variable 
      }else if(is_string($register->checkThumb())){ 
       $message = $register->checkThumb(); 

      } 
+0

爲什麼要投票? – crm 2012-07-08 12:48:07

回答

1
$thumb = $register->checkThumb(); //call method once and save in variable 
    /* using just if($thumb) would return always true, because 
     the function may returns an errormessage on failure 
     which is ja string, which is not empty, not 0, not false == true */ 
    if($thumb === true){ 
     //send image to permanent image directory 
     $register->moveUploadedImage(); 
    }else{ //so then it's enough to ask for error this way 
     $message = $thumb; 
    } 
1

你可以在if語句變量賦值,

if($checked = $register->checkThumb()){ 
    //send image to permanent image directory 
    $register->moveUploadedImage(); 

    //if the thumbnail failed validation put the error message in variable 
}else if(is_string($checked)){ 
    $message = $checked; 

} 
1

你可以做如下:

if(!($check_thumb_retvalue = $register->checkThumb())) { 
    //send image to permanent image directory 
    $register->moveUploadedImage(); 

//if the thumbnail failed validation put the error message in variable 
} 
else if(is_string($check_thumb_retvalue)) { 
    $message = $register->checkThumb(); 
} 

,或者更可讀:

$check_thumb_retvalue = $register->checkThumb(); 
if(!$check_thumb_retvalue){ 
    //send image to permanent image directory 
    $register->moveUploadedImage(); 
} 
//if the thumbnail failed validation put the error message in variable 
else if(is_string($check_thumb_retvalue)) { 
    $message = $check_thumb_retvalue; 
} 

LG, CK

1

你可以這樣做:

 $result = $register->checkThumb(); 
     if($result){ 
      //send image to permanent image directory 
      $register->moveUploadedImage(); 

      //if the thumbnail failed validation put the error message in variable 
     }else if(is_string($result)){ 
      $message = $result; 

     } 

但你的代碼是好的,除非方法有不會是任何顯着的區別,在所有非常昂貴。

1

您可以將結果賦值給變量,然後檢查該變量。 另外,當你檢查變量是否爲真時,你應該用operator ===來完成。否則,如果函數返回非空字符串,它也將被限定爲true。運算符===檢查類型,這樣只有值true的布爾變量纔會通過。

$result = $register->checkThumb(); 
if($result === true) { 
    $register->moveUploadedImage(); 
} else if (is_string($result)){ 
    $message = $result; 
}