2

我正在使用此代码并且它有效。事实是我不知道如何在没有 goto 的情况下更有效地重写它。我个人认为在这种情况下使用 goto (php 中的新功能)是可以的,但其他人告诉我这不行。我应该如何在没有 goto 的情况下重写我的代码?为什么你认为我的代码在 goto 方面不好?我不是经验丰富的程序员,所以任何我做错了什么的建议都值得赞赏。

    check_process:
    $random_code = substr(number_format(time() * rand(),0,'',''),0,10);

    $unique_check = $wpdb->get_var(
      "SELECT meta_id 
      FROM {$wpdb->postmeta} 
      WHERE meta_key = 'unique_code' 
      AND meta_value = '{$random_code}' 
      LIMIT 1"
    );

    if ($unique_check == NULL) {
       // OK
    }
    else {
        goto check_process; // go back and generate another unique code if are same
    }
4

6 回答 6

1
do{
    $random_code = substr(number_format(time() * rand(),0,'',''),0,10);

    $unique_check = $wpdb->get_var(
      "SELECT meta_id 
      FROM {$wpdb->postmeta} 
      WHERE meta_key = 'unique_code' 
      AND meta_value = '{$random_code}' 
      LIMIT 1"
    );
} while ( ! is_null($unique_check));
于 2013-08-07T07:47:29.943 回答
0
do {

...

} while {!is_null($unique_check))

我想你可以无休止地争论它,但我更喜欢这种风格而不是 goto :)

于 2013-08-07T07:47:41.487 回答
0

这看起来像是 a 的工作while

$check = true;
while($check){
    //do the stuff
    if($unique_check == NULL){
        $check = false;
    }
}

更简单的是do-while

do {
    //do the stuff
} while($unique_check != NULL);
于 2013-08-07T07:48:18.117 回答
0

使用do while循环怎么样?

do {
  $random_code = substr(number_format(time() * rand(),0,'',''),0,10);

  $unique_check = $wpdb->get_var(
    "SELECT meta_id 
    FROM {$wpdb->postmeta} 
    WHERE meta_key = 'unique_code' 
    AND meta_value = '{$random_code}' 
    LIMIT 1"
  );

} while (!is_null($unique_check)); // go back and generate another unique code if are same

使用这种循环而不是 goto 会更干净。

于 2013-08-07T07:50:33.767 回答
0

很长一段时间goto以来,人们一直不赞成,当您使用goto中断时,结构会exit在代码中创建多个点,从理论上讲,这真的很糟糕。替代方案goto回到gosub了过去,不同之处在于 gosub 在完成它正在做的事情后总是返回到调用点。所以今天gosub就像函数一样。

但是如果你反汇编一些代码并阅读汇编指令,你会发现数百个jmp与 goto 完全一样的引用。所以去图吧。

于 2013-08-07T07:52:46.543 回答
0

goto 可能是一个简单的选择,但就像你说的那样是不好的做法!

主要原因不是一点点,而是质量。如果你太熟悉它,你会经常使用它。对于试图阅读和理解您的代码的其他开发人员来说,这是一个问题。事实上,一个 goto 很容易,但想象至少 10 个。理解这个“意大利面条代码”将需要更多时间。

更好的做法是使用函数“跳转”到代码中的特定算法,如果可能的话,使用其他答案中的循环。

在这里你可以看到如果你使用 goto 会发生什么:D http://xkcd.com/292/

于 2013-08-07T07:54:32.520 回答