2

我有一个用户注册脚本。在一个阶段,我将一个方法调用了 3 次。一次检查该方法是否返回 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();

            }
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

您可以将结果分配给变量,然后检查该变量。此外,当您检查变量是否为真时,您应该使用运算符 === 进行检查。否则,如果函数返回非空字符串,它也将被限定为 true。运算符 === 检查类型,因此只有值为 true 的布尔变量才会通过。

$result = $register->checkThumb();
if($result === true) {
    $register->moveUploadedImage();
} else if (is_string($result)){
    $message = $result;
}
于 2012-07-08T12:54:33.053 回答
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 回答