What is the value returned by theme_get_registry, and why is it not NULL? I was going through Drupal code, and in the theme.inc file I found something that I couldn't understand. On theme(), I see the following code:

if (!isset($hooks)) {
  init_theme();
  $hooks = theme_get_registry();
}


theme_get_registry() is defined as follows:

function theme_get_registry($registry = NULL) {

  static $theme_registry = NULL;
  if (isset($registry)) {
    $theme_registry = $registry;
  }
  return $theme_registry;
}


I found the function is calling without any parameter, and the default parameter is NULL, but when I use print_r($registry) in the first line of the function theme_get_registry(), I get the values popped out; I assume the value should be NULL because it is not passing any value, and default value is NULL, from where $registry got values in the first line.
The value returned from theme_get_registry() is initialized by _theme_set_registry(), which is called by _theme_load_registry(), which is called by _init_theme(), called by init_theme().

function _theme_set_registry($registry) {
  // Pass through for setting of static variable.
  return theme_get_registry($registry);
}


init_theme() is called from theme(), right before calling theme_get_registry().

  $args = func_get_args();
  $hook = array_shift($args);

  static $hooks = NULL;
  if (!isset($hooks)) {
    init_theme();
    $hooks = theme_get_registry();
  }


The value used by theme_get_registry() ($theme_registry) is a static value; this means that the value theme_get_registry() gets from _theme_set_registry() is then returned all the times theme_get_registry() is called. NULL is the default value for $theme_registry, until $theme_registry = $registry is executed, and the calling function uses a value different from the default one.

To notice that the declaration of a static variable is different from the declaration of other local variables used by a function.

If I declare a variable as static $registry = NULL it doesn't mean the variable is always set to NULL. The constant value used in the declaration is the value assigned to the variable when it is initialized; the second time the function is called, its static variables are not initialized anymore, but they retain the value they had in the previous call of the function.
As reported in Variable scope:

function test() {
  $a = 0;
  echo $a;
  $a++;
}



  This function is quite useless since every time it is called it sets $a to 0 and prints 0. The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:


function test() {
  static $a = 0;
  echo $a;
  $a++;
}



  Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it.