Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

PHP static counter variable (not in function)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

static is only for use in functions:

A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.

There are undoubtedly better ways based on the application structure and how you call the view etc.. but since this is a single execution of a script but multiple includes of the view file, you can use a global variable:

$GLOBALS['counter'] = ++$GLOBALS['counter'] ?? 0;
$counter = $GLOBALS['counter'];

If $GLOBALS['counter'] is set then it will be incremented, if not it will be set to 0, then assigned to $counter.

For PHP < 7.0.0:

$GLOBALS['counter'] = isset($GLOBALS['counter']) ? ++$GLOBALS['counter'] : 0;
$counter = $GLOBALS['counter'];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...