2

ユーザー登録スクリプトがあります。ある段階で、メソッドを3回呼び出します。メソッドがtrueを返すかどうかを確認する場合、そうでない場合は文字列(エラーメッセージを含む)を返すかどうか、および返された文字列を取得して変数に配置するかどうかを確認します。

これを行うためのより生産的な方法で、メソッドを1回呼び出すだけで済みますか?しかし、それでも私が必要とするすべての答えを得ることができますか?

コードは次のとおりです。

//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();

            }
4

5 に答える 5

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;

}
于 2012-07-08T12:44:47.117 に答える
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;
    }
于 2012-07-08T12:45:37.787 に答える
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

于 2012-07-08T12:45:40.813 に答える
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;

        }

ただし、メソッドが非常に高価でない限り、コードは問題ありません。目立った違いはまったくありません。

于 2012-07-08T12:46:04.470 に答える
1

結果を変数に割り当ててから、その変数を確認できます。また、変数がtrueであるかどうかを確認するときは、演算子===を使用して行う必要があります。それ以外の場合、関数が空でない文字列を返すと、trueとしても修飾されます。演算子===は型をチェックするため、値trueのブール変数のみが渡されます。

$result = $register->checkThumb();
if($result === true) {
    $register->moveUploadedImage();
} else if (is_string($result)){
    $message = $result;
}
于 2012-07-08T12:54:33.053 に答える