我在这里使用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循环无休止地迭代。任何人都可以提出任何明显错误的内容吗?
答案 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
。