Function decreases static variable step by step, but it should not. PHP -


there function:

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

this code produces: 123456789109876543210

when $count increments 10 - understandable, works until if statement evaluates false. why gradually decreases 0? in newbie logic, $count-- in code should decrease 9 1 time , function should stop. there no loop or cycle can reduce value step step. see, here , working. why happens?

perhaps things bit clearer when change output emphasis how conditional recursive call works:

<?php function test($level=0) {     static $count = 0;     $count++;     echo str_pad('a:', $level+2, ' ', str_pad_left), $count, php_eol;      if ($count < 10) {         test($level+1);     }      $count--;     echo str_pad('b:', $level+2, ' ', str_pad_left), $count, php_eol; }  test(); 

prints

a:1  a:2   a:3    a:4     a:5      a:6       a:7        a:8         a:9          a:10          b:9         b:8        b:7       b:6      b:5     b:4    b:3   b:2  b:1 b:0 

your problem seems understanding how function call(s) , subsequent return(s) function works. let's start simple

<?php function c() {     echo 'c in', php_eol;     echo 'c out', php_eol; }  function b() {     echo 'b in', php_eol;     c();     echo 'b out', php_eol; }  function a() {     echo 'a in', php_eol;     b();     echo 'a out', php_eol; }  a(); 

prints

a in b in c in c out b out out 

easy enought, isn't it? when function exits/returns execution continues @ point call made. , isn't bound name of function, function call itself, see e.g. https://en.wikipedia.org/wiki/call_stack .
if function calls like

<?php function foo($param) {     echo "foo($param) in", php_eol;     if ( $param!==1 ) {         foo(1);     }     echo "foo($param) out", php_eol; }  foo(0); 

that doesn't cause single exit/return cancel function calls of "same" function, bubbles 1 "scope"/frame in call stack. therefore output is

foo(0) in foo(1) in foo(1) out foo(0) out 

now compare output of "improved" script above: hope clears things bit you.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo