Home >Backend Development >PHP Tutorial >Recursion on a static variable

Recursion on a static variable

WBOY
WBOYOriginal
2016-09-08 08:44:091867browse

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

    echo $count++;
    if ($count < 10) {
        test();
    }
    echo $count--;
}
?></code>

Result: 012345678910987654321
The echo $cont++ in the first half, I can understand why echo $count--it starts from 10. Press from top to bottom, ++ --doesn’t it offset?

Reply content:

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

    echo $count++;
    if ($count < 10) {
        test();
    }
    echo $count--;
}
?></code>

Result: 012345678910987654321
The echo $cont++ in the first half, I can understand why echo $count--it starts from 10. Press from top to bottom, ++ --doesn’t it offset?

This is the entry and exit sequence of the stack

If function is called inside, the following cannot be executed until the count>10 function call is completed.

The first 10 recursions did not execute echo $count--;, because the recursive call has not ended yet. Until $count == 10, there will be no more recursion, so it is completed layer by layer Recursive operation

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn