Hello If I'm not mistaken, this code should output 1 2 3 4 5 if x is equal to asc and 9 8 7 6 5 if x is not equal to asc.

<?php $x = 'asc'; function fun() { if($GLOBALS['x'] == 'asc') { static $counter = 0; $counter++; echo "$counter<br>"; } else { static $counter = 10; $counter--; echo "$counter<br>"; } } fun(); fun(); fun(); fun(); fun(); ?> 

But it displays 11 12 13 14 15 if x is equal to asc and 9 8 7 6 5 if x is not equal to asc. Why the condition does not work and in any case, the counter is set to 10?

    1 answer 1

    Static values ​​are saved between function calls, so these variables are set before the first function call is performed with fun() .

    In this case, the last definition of the static variable $counter is taken, not paying attention to the internal logic of the function - the logic begins to work later, when called. Therefore, your $counter value always starts with 10.

     static $counter = 10;