简体   繁体   English

在函数内部重用相同的函数

[英]Reuse Same Function inside a Function

I've been thinking of the best way to create a dynamically nested 我一直在思考创建动态嵌套的最佳方法

    navigation using PHP, and that is to use a function that gets called within the same function to generate the different navigation levels. 使用PHP进行导航,即使用在同一函数中调用的函数来生成不同的导航级别。

    I have a database that consists of 3 fields: 我有一个包含3个字段的数据库:

  • page - Used as a unique identifier for the navigation item 页面-用作导航项的唯一标识符
  • title - Used to store the title of the navigation item. title-用于存储导航项的标题。
  • owner - used to store what page this page is associated to. 所有者-用于存储与此页面关联的页面。 (Parent page) (父页面)

I'm trying to make the followed menu dynamic 我正在尝试使后面的菜单动态化

<ul>
    <li><a href="#">Menu 1</a>
        <ul>
            <li><a href="#">Sub Menu 1</a></li>
            <li><a href="#">Sub Menu 2</a></li>
            <li><a href="#">Sub Menu 3</a></li>
            <li><a href="#">Sub Menu 4</a>
                <ul>
                    <li><a href="#">Sub Menu 1 of Sub Menu 4</li>
                    <li><a href="#">Sub Menu 2 of Sub Menu 4</li>
                    <li><a href="#">Sub Menu 3 of Sub Menu 4</li>
                </ul>
            </li>
        </ul>
    </li>
    <li><a href="#">Menu 2</a></li>
</ul>

I'm having issues, as the page crashes upon calling the function again inside the same function, as it creates a continuous loop. 我遇到了问题,因为页面在同一函数内再次调用该函数时崩溃,因为它创建了一个连续循环。 How do I prevent this from happening? 如何防止这种情况发生?

Thanks! 谢谢!

A function can simply call itself, by name. 函数可以通过名称简单地调用自身。

For example: (this is an actual method from one of my classes) 例如:(这是我的一个类中的实际方法)

protected function getParentName( $pid ) {

        foreach( $this->input as $a ) {
            if( $pid == $a['id'] ) {
                $this->bc = '<a href="/category/' . $a['id'] . '">' . $a['name'] . '</a> >> ' . $this->bc;
                if( !empty( $a['i_parent'] ) ) {
                    $this->getParentName( $a['i_parent'] );
                }
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM