多次调用一个方法,有没有更有效的方法呢?

时间:2012-07-08 12:40:27

标签: php class methods return

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

            }

5 个答案:

答案 0 :(得分: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 :(得分: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;
    }

答案 2 :(得分: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

答案 3 :(得分: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;

        }

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

答案 4 :(得分:1)

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

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