多次调用一个方法,是否有更有效的方法


calling a method multiple times, is there a more productive way of doing it?

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

您可以在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;
}

您可以执行以下操作:

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

你可以做:

        $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;
        }

但是你的代码很好,除非这个方法非常昂贵,否则根本不会有任何明显的差异。

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

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