Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confirmation that PHP static variables do not persist across requests

Tags:

php

I am looking for assurance that static variables are NOT stored between PHP requests. The following previous questions:

PHP static variables across multiple .php pages

Does static variables in php persist across the requests?

Static variables across sessions

clearly say that they aren't but they are more in the context of providing a way to maintain state rather than a specific discussion of what is the expected behaviour.

As an example, if I have PHP code as follows:

function myfunc()
{
    static $a=0;
    print $a++;
}

for ($i=0;$i<10;$i++) myfunc();

then I get output of 0123456789 every time I run it. My instinct/understanding of PHP makes me fairly sure that this has to be the case.

In my own experiments, I've shut a (preforking) apache down to one child to make sure that the variable isn't remembered between requests. It isn't remembered between requests as I'd expect. But this is only one scenario in which PHP runs.

What I'm looking for is:

A link to an official piece of documentation that says this is the expected behaviour and won't change. The relevant piece of PHP documentation doesn't mention this explicitly (except in the comments).

Or, an example of when static variables are remembered across requests such as webservers or performance enhancing PHP frameworks out there which will potentially not clear static variables to increase speed between requests.

like image 423
ADW Avatar asked Feb 03 '23 18:02

ADW


1 Answers

PHP does not preserve the application state between requests. During an PHP applications life cycle the application is freshly executed with each request. Static variables are meant to preserve the value of a variable in a local function scope when execution leaves the scope. Nowhere in the documentation does it mention that static variables are meant to preserve value across requests.

like image 139
GWW Avatar answered Feb 05 '23 06:02

GWW