Heim  >  Artikel  >  Backend-Entwicklung  >  求php一段递归代码的理解

求php一段递归代码的理解

WBOY
WBOYOriginal
2016-06-06 20:14:10963Durchsuche

<code class="php">function test()
{
    static $count = 0;

    $count++;
    echo "-- ".$count." --\n";
    if ($count </code>

结果输出如下:

<code class="php">-- 1 --
-- 2 --
-- 3 --
-- 4 --
-- 5 --
-- 6 --
-- 7 --
-- 8 --
-- 9 --
-- 10 --
## 9 ##
## 8 ##
## 7 ##
## 6 ##
## 5 ##
## 4 ##
## 3 ##
## 2 ##
## 1 ##
## 0 ##</code>

我的疑惑是 当$count加到10后就不会再调用自身了,那么它会运行下面的代码$count--然后输出就结束了,可是为什么它还是运行了9次呢,求高手解答。

回复内容:

<code class="php">function test()
{
    static $count = 0;

    $count++;
    echo "-- ".$count." --\n";
    if ($count </code>

结果输出如下:

<code class="php">-- 1 --
-- 2 --
-- 3 --
-- 4 --
-- 5 --
-- 6 --
-- 7 --
-- 8 --
-- 9 --
-- 10 --
## 9 ##
## 8 ##
## 7 ##
## 6 ##
## 5 ##
## 4 ##
## 3 ##
## 2 ##
## 1 ##
## 0 ##</code>

我的疑惑是 当$count加到10后就不会再调用自身了,那么它会运行下面的代码$count--然后输出就结束了,可是为什么它还是运行了9次呢,求高手解答。

这样吧,我们假设让$count小于2时来看看整个执行过程:

  1. 将小于10改为小于2:

<code> function test()
    {
        static $count = 0;
    
        $count++;
        echo "-- ".$count." --\n";
        if ($count </code>

2.将小于2时,里面递归的test()换成函数体内的代码:

<code>function test()
{
    static $count = 0;   // line 1
    $count++; // line 2
    echo "-- ".$count." --\n"; // line 3
    if ($count </code>

3.调用 test()后

<code>test()
</code>

4.来看整个详细的执行流程:

<code> 4.1 第一次,line 1:$count = 0;
 4.2 执行line 2后,$count = 1;
 4.3 所以在line 3 会输出: **-- 1 --**
 4.4 接着执行line 4,由于现在 $count </code>

5.总结:
当我们假定 $count小于2时,在上面详细的执行流程中我们看到:
test()总共被执行了2次,
输出结果为:
-- 1 --,-- 2 --,## 1 ##,## 0 ##
这时候再回头将 $count小于10,就容易解释楼主的疑问了。
不知道是否帮助到了你。有疑问继续联系。

没有再运行9次呀,test函数只运行了10次。但是每个函数中有两个输出,所以总共输出了20次。

有没有return不会停止,在调用他自己后还会继续执行的

因为当$count=10的时候,该段代码还是执行了,你可以这样写

<code>function test()
{
    static $count = 0;

    $count++;

    echo "-- ".$count." --<br>";
    if ($count ";
    }

}
test();</code>

@phping 这是我对于刚才递归的理解,和你的类似。

<code class="php">function test() {
    static $count = 0; // 初始化静态变量$count
    $count++; // $count = 1;
    echo "-- ".$count." --\n"; // 输出 1
    if($count </code>

最后输出

<code class="php">-- 1 --
-- 2 --
-- 3 --
## 2 ##
## 1 ##
## 0 ##</code>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn