`static` keyword inside function?

user151841 picture user151841 · May 31, 2011 · Viewed 55.9k times · Source

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

Answer

Yoshi picture Yoshi · May 31, 2011

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:

function doStuff() {
  static $cache = null;

  if ($cache === null) {
     $cache = '%heavy database stuff or something%';
  }

  // code using $cache
}

In this example, the if would only be executed once. Even if multiple calls to doStuff would occur.