PHP函数调用导致无限递归

时间:2017-01-17 15:25:03

标签: php recursion tree

函数nested()返回嵌套元素的数组,而这些元素又是与父类相同的类的实例。

函数drop()包含匿名函数push(),它以递归方式遍历树,但由于某种原因,它会导致无限循环,我无法弄清楚原因。我使用条件count($set) > 0来阻止无限递归,因此当它到达树的末尾时它可能会停止递归调用push()函数,但它不会停止。

public function nested() {
    $list = [];
    $categories = Db::o()->select("categories(c)", [
            "[><]_categories(_c)" => ["c.id" => "child"]
        ], [
            "c.id",
            "c.title",
            "c.alias"
        ], [
            "_c.parent" => $this->id
    ]);

    foreach($categories as $category) {
        $list[] = new Category($category['id'], $category['title'], $category['alias']);
    }
    return $list;
}

public function drop() {
    $push = function ($set) use (&$push) {
        if (count($set) > 0) {
            foreach($set as $child) {
                $this->subset .= $child->id;
                $push($child->nested());
            }
        }
    };

    $push($this->nested());
    $this->dropSubset();
}

0 个答案:

没有答案