We have a view in our project that looks something like this
<?php
static $counter = 0;
$counter++
?>
<div id="item_<?= $counter ?>"> Item <?= $counter ?> </div>
The view is called multiple times per request, but the counter value always seems to be 1
This behaviour is somewhat different to the documented behaviour for static variables within a function*, but I couldn't find any documentation on static variables outside of functions or classes
What is happening here? Why does this pattern work within a function but not outside? Does the static keyword have any value in this scope?
*https://www.php.net/manual/en/language.variables.scope.php#language.variables.scope.static
UPDATE
On further investigation, and following some of the answers..
I think the views are effectively being 'inlined' one after another in the main script, so aren't scoped in the same way as a function that is declared once and then called multiple times
I would expect the same non-incrementing behaviour if I repeatedly declared and incremented the static counter twice in the same function
So my guess is that static variables outside functions aren't 'wrong' exactly, but do not have a valid use case
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…