首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PHP手册示例#6带有递归函数的静态变量变化范围理解

PHP手册示例#6带有递归函数的静态变量变化范围理解
EN

Stack Overflow用户
提问于 2015-03-10 20:28:20
回答 1查看 73关注 0票数 1

事先道歉(这里的新手),但试图理解和有一个困难的时间找到一个与此直接相关的话题。我使用php手册中的递归函数对示例#6的静态变量进行了修改

http://php.net/manual/en/language.variables.scope.php

代码语言:javascript
运行
复制
<?php

    function test() {
        static $count = 0;
        $count++;
        echo $count;
        if ($count < 10) {
            test();
        }
        $count--;
        echo $count;
    }
    
    test();

?>

输出为123456789109876543210

我期望它在if语句之外的9处停止,并且会减少。(例如)123456789109

我显然不了解静态范围和代码流。我真的应该想出一个调试器,但是有什么指针吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-10 21:16:13

也许这个小小的改动能帮助你更好地理解。

为什么它不停止后,它到9以外的if语句?

因为每个测试的调用都会一直运行到最后。它增加了10倍,减少了10倍。第一次增加10倍,因为10次调用测试,在第10次调用中,测试开始。第10次呼叫结束,第9次呼叫减少。第9次通话结束,第8次通话减少.

代码语言:javascript
运行
复制
<?php
function test()
{
    static $count = 0;

    $count++;
    echo $count.". call of test() (output after incrementing)<br />";
    if ($count < 10) {
        test();
    }
    echo $count.". call of test() (output before decrementing)<br />";
    $count--;
}

test();
?>

输出:

代码语言:javascript
运行
复制
1. call of test() (output after incrementing)
2. call of test() (output after incrementing)
3. call of test() (output after incrementing)
4. call of test() (output after incrementing)
5. call of test() (output after incrementing)
6. call of test() (output after incrementing)
7. call of test() (output after incrementing)
8. call of test() (output after incrementing)
9. call of test() (output after incrementing)
10. call of test() (output after incrementing)
10. call of test() (output before decrementing)
9. call of test() (output before decrementing)
8. call of test() (output before decrementing)
7. call of test() (output before decrementing)
6. call of test() (output before decrementing)
5. call of test() (output before decrementing)
4. call of test() (output before decrementing)
3. call of test() (output before decrementing)
2. call of test() (output before decrementing)
1. call of test() (output before decrementing)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28973490

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档