如何在 PHP 中以递归方式调用函数

How to call function in recursive manner in PHP

我正在尝试创建一个动态 header,为此我在 class 函数中使用递归逻辑。

我在视图端使用它。

    <nav class="primary-menu uppercase">
      <ul class="clearfix">
        <li class="current"><a href="/">Home</a></li>
        <?php
                include("modules/listMenu.php");
                $list->menu(0);
        ?>
        <li><a href="/contact">Contact</a></li>
      </ul>
    </nav>

下面是class中使用的代码m。

class listMenu Extends Connection
    {
        public function menu($parent_id)
            {
                $query = ' SELECT id, name, slug FROM categories WHERE status = 1 AND parent_id = "'.$parent_id.'" ';
                $connection = $this->establish_connection();
                $data = $connection->query($query);
                $connection->close();
                if($data->num_rows > 0)
                    {
                        while($row = $data->fetch_assoc())
                            {
                                // print_r($row);
                                // exit();
                                $menu .="<li><a href='".$row['slug']."'>".$row['name']."</a>";
                                $menu .= "<ul>".$this->menu($row['id'])."</ul>"; //call  recursively
                                $menu .= "</li>";
                            }

                        return $menu;
                    }
            }
    }

$list = new listMenu();

我正在使用 $this->menu($row['id']) 递归地实现回避登录,但是收到一个错误提示 NOTICE: UNDEFINED VARIABLE: MENU

这个错误的原因是什么。我错过了什么?

我认为会有帮助

class listMenu Extends Connection
{
    public function menu($parent_id)
        {
            $query = ' SELECT id, name, slug FROM categories WHERE status = 1 AND parent_id = "'.$parent_id.'" ';
            $connection = $this->establish_connection();
            $data = $connection->query($query);
            $connection->close();
            if($data->num_rows > 0)
                {
                    $menu = '';
                    while($row = $data->fetch_assoc())
                        {
                            $menu .="<li><a href='".$row['slug']."'>".$row['name']."</a>";
                            $menu .= "<ul>".$this->menu($row['id'])."</ul>"; //call  recursively
                            $menu .= "</li>";
                        }

                    return $menu;
                }
        }
}

$list = new listMenu();