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

Recursion on a static variable

WBOY
Release: 2016-09-08 08:44:09
Original
1840 people have browsed it

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

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

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>
Copy after login
Copy after login

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

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template