I was looking at the source for Drupal 7, and I found some things I hadn't seen before. I did some initial looking in the php manual, but it didn't explain these examples.
What does the keyword static
do to a variable inside a function?
function module_load_all($bootstrap = FALSE) {
static $has_run = FALSE
static variable in a function means that no matter how many times you call the function, there's only 1 variable.
Seems like nobody mentioned so far, that static variables inside different instances of the same class remain their state. So be careful when writing OOP code.
Consider this:
If you want a static variable to remember its state only for current class instance, you'd better stick to a class property, like this:
Static works the same way as it does in a class. The variable is shared across all instances of a function. In your particular example, once the function is run, $has_run is set to TRUE. All future runs of the function will have $has_run = TRUE. This is particularly useful in recursive functions (as an alternative to passing the count).
See http://php.net/manual/en/language.variables.scope.php
It makes the function remember the value of the given variable (
$has_run
in your example) between multiple calls.You could use this for different purposes, for example:
In this example, the
if
would only be executed once. Even if multiple calls todoStuff
would occur.Given the following example:
First call of
will output
10
, then$v
to be20
. The variable$v
is not garbage collected after the function ends, as it is a static (non-dynamic) variable. The variable will stay within its scope until the script totally ends.Therefore, the following call of
will then output
20
, and then set$v
to be15
.To expand on the answer of Yang
If you extend a class with static variables, the individual extended classes will hold their "own" referenced static that's shared between instances.
outputs:
http://ideone.com/W4W5Qv