虽然循环不应该迭代

时间:2016-02-14 15:46:49

标签: php

我在这里使用WordPress。我有以下函数,它从函数外部调用,然后通过while循环递归调用。

    public function parent_category_has_fiance($cat_id) {
        global $wpdb;
        $terms = $wpdb->get_row("
                            SELECT
                                term_id, 
                                parent 
                            FROM
                                $wpdb->term_taxonomy
                            WHERE 
                                term_id = $cat_id
                                ");

        $terms = int($terms->parent);
        //var_dump($terms);

        while ($terms > 0) {
            //do some logic
            $parent_id = $terms->parent;
            $this->parent_category_has_fiance($parent_id);
        }
    }   

然而,当$terms等于0时,while循环无休止地迭代。任何人都可以提出任何明显错误的内容吗?

2 个答案:

答案 0 :(得分:3)

无限循环的原因很简单。

从不更新循环体内$terms的值,这是在循环条件下使用的。

因此循环体执行零次或无限次。

此修补程序似乎将while替换为if,因为您已通过递归调用处理父级。但是,我可能错了,因为你的功能没有返回任何东西,似乎没有副作用......

答案 1 :(得分:1)

误解在于$terms变量的范围。此变量的作用域是它存在的函数调用的本地。循环

while ($terms > 0) {
    //do some logic
    $parent_id = $terms->parent;
    $this->parent_category_has_fiance($parent_id);
}

引用了$terms变量,但是当调用parent_category_has_fiance时,该函数内的$terms变量只存在于那里。也就是说,它不会改变while循环正在查看的$terms