The variable_set()
and variable_get()
functions are made to set/get a persistent variable. So they should not be used to persist data within a single page request. The drupal_static()
function is made for this task and is well documented. Off course, you could also go with a static variablestatic variable without bothering about drupal_static()
. But drupal_static()
will make your code more maintainable and future proof.
/**
* Set or get the shared foo variable.
*
* @param $new_value
* (optional) If set, the new value to assign to the foo variable.
*
* @return
* The value of the foo variable. If $new_value is set this would be
* the previous value.
*/
function MODULE_foo($new_value = NULL) {
$value = drupal_static(__FUNCTION__, NULL);
$previous_value = $value;
if ($new_value !== NULL) {
$value = $new_value;
}
return $previous_value;
}