【问题标题】:Puzzling recursion with php令人费解的 php 递归
【发布时间】:2012-10-31 22:17:58
【问题描述】:

我将此代码与 php 一起使用:

while (0 != $date1 || $this->counter < 5 ) {
    // if ($this->true_cahce_failure ) {
    $this->url= $this->adjust_url_with_www_add($this->url);
    // $this->counter=2;
    // }

    $this->cache_debug("Date".$date1." ".$this->url,"Recursion ".$this->counter);
    $date1 = $this->get_date();
    $this->counter++;
}
$this->cache_debug("Date: ".$date1." ".$this->url,"Loop Done ");

基本上循环应该一直持续到$datenot 0counter 不大于5。有时date10,但有时没有。如果不是,它应该在 while 评估中返回,并停止迭代。但它并没有这样做,迭代仍在继续。

只有当计数器达到 5 时才会停止。这是为什么呢?

【问题讨论】:

    标签: php recursion while-loop conditional-statements


    【解决方案1】:

    我认为您想在您的情况下使用&amp;&amp; 而不是||

    如果任一条件为真,您编写它的方式将继续运行,因此只有当它们都为假时才会停止。

    编辑:仔细阅读您的问题后,我认为您需要使用

    while (0 == $date1 && $this->counter < 5 ) {
    

    【讨论】:

    • 它没有工作.. 它在第一次迭代时退出 //.. 当日期为 0 时
    【解决方案2】:

    它可能不会停止,因为当 $date1 不是 0 时,您的 $this-&gt;counter 仍然是 &lt; 5。如果您查看这些语句的 true/false 值,您的 while 条件变为:

    while( false || true )
    

    $this-&gt;counter&lt; 5 并且对于$date 的任何值,这将使执行继续。

    你可能想把它切换到

    while( 0==$date1 && $this->counter<5 )
    

    使用&amp;&amp;,因为您希望两个条件都是true,而不仅仅是一个。在将日期与0 进行比较时,还将!= 切换为==,因此当您有非0 日期时它也会停止。

    【讨论】:

    • 好的,我用了这个:while( strlen($date1)counter
    猜你喜欢
    • 2014-02-13
    • 2021-09-02
    • 2011-07-20
    • 2011-10-07
    • 2010-10-01
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多