1. drupal
    1. 8
    2. 7
7 – 8 &drupal_static($name, $default_value = NULL, $reset = FALSE)

Central static variable storage.

All functions requiring a static variable to persist or cache data within a single page request are encouraged to use this function unless it is absolutely certain that the static variable will not need to be reset during the page request. By centralizing static variable storage through this function, other functions can rely on a consistent API for resetting any other function's static variables.


function language_list($field = 'language') {
  $languages = &drupal_static(__FUNCTION__);
  if (!isset($languages)) {
    // If this function is being called for the first time after a reset,
    // query the database and execute any other code needed to retrieve
    // information about the supported languages.
  if (!isset($languages[$field])) {
    // If this function is being called for the first time for a particular
    // index field, then execute code needed to index the information already
    // available in $languages by the desired field.
  // Subsequent invocations of this function for a particular index field
  // skip the above two code blocks and quickly return the already indexed
  // information.
  return $languages[$field];
function locale_translate_overview_screen() {
  // When building the content for the translations overview page, make
  // sure to get completely fresh information about the supported languages.

In a few cases, a function can have certainty that there is no legitimate use-case for resetting that function's static variable. This is rare, because when writing a function, it's hard to forecast all the situations in which it will be used. A guideline is that if a function's static variable does not depend on any information outside of the function that might change during a single page request, then it's ok to use the "static" keyword instead of the drupal_static() function.


function actions_do(...) {
  // $stack tracks the number of recursive calls.
  static $stack;
  if ($stack > variable_get('actions_max_stack', 35)) {

In a few cases, a function needs a resettable static variable, but the function is called many times (100+) during a single page request, so every microsecond of execution time that can be removed from the function counts. These functions can use a more cumbersome, but faster variant of calling drupal_static(). It works by storing the reference returned by drupal_static() in the calling function's own static variable, thereby removing the need to call drupal_static() for each iteration of the function. Conceptually, it replaces:

$foo = &drupal_static(__FUNCTION__);


// Unfortunately, this does not work.
static $foo = &drupal_static(__FUNCTION__);

However, the above line of code does not work, because PHP only allows static variables to be initializied by literal values, and does not allow static variables to be assigned to references.

The example below shows the syntax needed to work around both limitations. For benchmarks and more information, see http://drupal.org/node/619666.


function user_access($string, $account = NULL) {
  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
  $perm = &$drupal_static_fast['perm'];


$name Globally unique name for the variable. For a function with only one static, variable, the function name (e.g. via the PHP magic __FUNCTION__ constant) is recommended. For a function with multiple static variables add a distinguishing suffix to the function name for each one.

$default_value Optional default value.

$reset TRUE to reset a specific named variable, or all variables if $name is NULL. Resetting every variable should only be used, for example, for running unit tests with a clean environment. Should be used only though via function drupal_static_reset() and the return value should not be used in this case.

Return value

Returns a variable by reference.

See also


▾ 176 functions call drupal_static()

actions_list in includes/actions.inc
Discovers all available actions by invoking hook_action_info().
actions_loop_test_log in modules/simpletest/tests/actions_loop_test.module
Write a message to the log.
aggregator_category_load in modules/aggregator/aggregator.module
Load an aggregator category.
aggregator_feed_load in modules/aggregator/aggregator.module
Load an aggregator feed.
archiver_get_info in includes/common.inc
Retrieves a list of all available archivers.
arg in includes/bootstrap.inc
Return a component of the current Drupal path.
block_admin_display_prepare_blocks in modules/block/block.admin.inc
Prepares a list of blocks for display on the blocks administration page.
block_list in modules/block/block.module
Return all blocks in the specified region for the current user.
book_get_books in modules/book/book.module
Returns an array of all books.
book_get_flat_menu in modules/book/book.module
Get the book menu tree for a page, and return it as a linear array.
book_menu_subtree_data in modules/book/book.module
Get the data representing a subtree of the book hierarchy.
BootstrapResettableStaticTestCase::testDrupalStatic in modules/simpletest/tests/bootstrap.test
Test that a variable reference returned by drupal_static() gets reset when drupal_static_reset() is called.
comment_node_update_index in modules/comment/comment.module
Implements hook_node_update_index().
conf_path in includes/bootstrap.inc
Finds the appropriate configuration directory.
dashboard_regions in modules/dashboard/dashboard.module
Return an array of dashboard region names.
DrupalWebTestCase::checkPermissions in modules/simpletest/drupal_web_test_case.php
Check to make sure that the array of permissions are valid.
drupal_add_css in includes/common.inc
Adds a cascading stylesheet to the stylesheet queue.
drupal_add_feed in includes/common.inc
Add a feed URL for the current page.
drupal_add_html_head in includes/common.inc
Add output to the head tag of the HTML page.
drupal_add_http_header in includes/bootstrap.inc
Set an HTTP response header for the current page.
drupal_add_js in includes/common.inc
Adds a JavaScript file, setting, or inline code to the page.
drupal_add_library in includes/common.inc
Adds multiple JavaScript or CSS files at the same time.
drupal_add_tabledrag in includes/common.inc
Assist in adding the tableDrag JavaScript behavior to a themed table.
drupal_alter in includes/module.inc
Hands off alterable variables to type-specific *_alter implementations.
drupal_cache_system_paths in includes/path.inc
Cache system paths for a page.
drupal_get_destination in includes/common.inc
Prepare a 'destination' URL query parameter for use in combination with drupal_goto().
drupal_get_filetransfer_info in includes/common.inc
Drupal FileTransfer registry.
drupal_get_http_header in includes/bootstrap.inc
Get the HTTP response headers for the current page.
drupal_get_library in includes/common.inc
Retrieves information for a JavaScript/CSS library.
drupal_get_schema_versions in includes/install.inc
Returns an array of available schema versions for a module.
drupal_get_updaters in includes/common.inc
Drupal Updater registry.
drupal_html_id in includes/common.inc
Prepare a string for use as a valid HTML ID and guarantee uniqueness.
drupal_is_front_page in includes/path.inc
Check if the current page is the front page.
drupal_lookup_path in includes/path.inc
Given an alias, return its Drupal system URL if one exists. Given a Drupal system URL return one of its aliases if such a one exists. Otherwise, return FALSE.
drupal_mail_system in includes/mail.inc
Returns an object that implements the MailSystemInterface.
drupal_match_path in includes/path.inc
Check if a path matches any pattern in a set of patterns.
drupal_page_header in includes/bootstrap.inc
Set HTTP headers in preparation for a page response.
drupal_page_is_cacheable in includes/bootstrap.inc
Determine the cacheability of the current page.
drupal_parse_info_file in includes/common.inc
Parses Drupal module and theme .info files.
drupal_render_collect_attached in includes/common.inc
Collect #attached for an element and all child elements into a single array.
drupal_render_page in includes/common.inc
Renders the page, including all theming.
drupal_retrieve_form in includes/form.inc
Retrieves the structured array that defines a given form.
drupal_save_session in includes/session.inc
Determines whether to save session data of the current request.
drupal_send_headers in includes/bootstrap.inc
Send the HTTP response headers previously set using drupal_add_http_header(). Add default headers, unless they have been replaced or unset using drupal_add_http_header().
drupal_set_breadcrumb in includes/common.inc
Set the breadcrumb trail for the current page.
drupal_set_page_content in includes/common.inc
Set the main page content value for later use.
drupal_set_title in includes/bootstrap.inc
Set the title of the current page, for display on the page and in the title bar.
drupal_static_reset in includes/bootstrap.inc
Reset one or all centrally stored static variable(s).
drupal_validate_form in includes/form.inc
Validates user-submitted form data from the $form_state using the validate functions defined in a structured form array.
element_info in includes/common.inc
Retrieve the default properties for the defined element type.
entity_get_controller in includes/common.inc
Get the entity controller class for an entity type.
entity_get_info in includes/common.inc
Get the entity info array of an entity type.
field_available_languages in modules/field/field.multilingual.inc
Collects the available languages for the given entity type and field.
field_language in modules/field/field.multilingual.inc
Returns the display language for the fields attached to the given entity.
field_test_entity_info_translatable in modules/field/tests/field_test.entity.inc
Helper function to enable entity translations.
field_test_memorize in modules/field/tests/field_test.module
Store and retrieve keyed data for later verification by unit tests.
field_ui_field_type_options in modules/field_ui/field_ui.admin.inc
Return an array of field_type options.
field_ui_formatter_options in modules/field_ui/field_ui.admin.inc
Return an array of formatter options for a field type.
field_ui_widget_type_options in modules/field_ui/field_ui.admin.inc
Return an array of widget type options for a field type.
field_view_mode_settings in modules/field/field.module
Returns view mode settings in a given bundle.
file_get_file_references in modules/file/file.module
Gets a list of references to a file.
file_get_stream_wrappers in includes/file.inc
Drupal stream wrapper registry.
file_mimetype_mapping in includes/file.mimetypes.inc
Return an array of MIME extension mappings.
file_test_file_scan_callback in modules/simpletest/tests/file.test
Helper function for testing file_scan_directory().
filter_formats in modules/filter/filter.module
Retrieve a list of text formats, ordered by weight.
filter_get_filters in modules/filter/filter.module
Return a list of all filters provided by modules.
filter_list_format in modules/filter/filter.module
Retrieve a list of filters for a given text format.
format_date in includes/common.inc
Formats a date, using a date type or a custom date format string.
form_set_error in includes/form.inc
Files an error against a form element.
forum_field_storage_pre_update in modules/forum/forum.module
Implements hook_field_storage_pre_update().
forum_forum_load in modules/forum/forum.module
Returns a tree of all forums for a given taxonomy term ID.
hook_field_storage_pre_update in modules/field/field.api.php
Act before the storage backends update field data.
hook_field_update in modules/field/field.api.php
Define custom update behavior for this module's field types.
image_effects in modules/image/image.module
Load all image effects from the database.
image_effect_definitions in modules/image/image.module
Pull in image effects exposed by modules implementing hook_image_effect_info().
image_styles in modules/image/image.module
Get an array of all styles and their settings.
install_profile_info in includes/install.inc
Retrieve info about an install profile from its .info file.
ip_address in includes/bootstrap.inc
If Drupal is behind a reverse proxy, we use the X-Forwarded-For header instead of $_SERVER['REMOTE_ADDR'], which would be the IP address of the proxy server, and not the client's. The actual header name can be configured by the…
language_fallback_get_candidates in includes/language.inc
Return the possible fallback languages ordered by language weight.
language_list in includes/bootstrap.inc
Get a list of languages set up indexed by the specified key
language_negotiation_info in includes/language.inc
Return all the defined language providers.
language_provider_invoke in includes/language.inc
Helper function used to cache the language providers results.
language_types_configurable in includes/language.inc
Return only the configurable language types.
language_types_info in includes/language.inc
Return all the defined language types.
list_allowed_values in modules/field/modules/list/list.module
Returns the array of allowed values for a list field.
list_themes in includes/theme.inc
Return a list of all currently available themes.
locale in modules/locale/locale.module
Provides interface translation services.
locale_get_plural in modules/locale/locale.module
Returns plural form index for a specific number.
locale_language_name in modules/locale/locale.module
Returns a language name
locale_language_url_rewrite_url in includes/locale.inc
Rewrite URLs for the URL language provider.
locale_url_outbound_alter in modules/locale/locale.module
Implements hook_url_outbound_alter().
map_month in includes/form.inc
Helper function for usage with drupal_map_assoc to display month names.
menu_cache_clear in includes/menu.inc
Clears the cached cached data for a single named menu.
menu_contextual_links in includes/menu.inc
Retrieve contextual links for a system object based on registered local tasks.
menu_get_custom_theme in includes/menu.inc
Gets the custom theme for the current page, if there is one.
menu_get_item in includes/menu.inc
Get a router item.
menu_get_names in includes/menu.inc
Build a list of named menus.
menu_link_get_preferred in includes/menu.inc
Lookup the preferred menu link for a given system path.
menu_load_all in modules/menu/menu.module
Load all custom menu data.
menu_local_tasks in includes/menu.inc
Collects the local tasks (tabs), action links, and the root path.
menu_set_active_menu_names in includes/menu.inc
Set (or get) the active menu for the current page - determines the active trail.
menu_set_active_trail in includes/menu.inc
Sets the active trail (path to menu tree root) of the current page.
menu_tree in includes/menu.inc
Renders a menu tree based on the current path.
menu_tree_all_data in includes/menu.inc
Get the data structure representing a named menu tree.
menu_tree_page_data in includes/menu.inc
Get the data structure representing a named menu tree, based on the current page.
menu_tree_set_path in includes/menu.inc
Set the path for determining the active trail of the specified menu tree.
ModuleUnitTest::testModuleImplements in modules/simpletest/tests/module.test
Test module_implements() caching.
module_hook_info in includes/module.inc
Retrieve a list of what hooks are explicitly declared.
module_implements in includes/module.inc
Determine which modules are implementing a hook.
module_implements_write_cache in includes/module.inc
Writes the hook implementation cache.
node_access in modules/node/node.module
Determine whether the current user may perform the given operation on the specified node.
node_access_view_all_nodes in modules/node/node.module
Determines whether the user has a global viewing grant for all nodes.
node_last_viewed in modules/node/node.module
Retrieves the timestamp at which the current user last viewed the specified node.
node_mark in modules/node/node.module
Decide on the type of marker to be displayed for a given node.
overlay_display_empty_page in modules/overlay/overlay.module
Callback to request that the overlay display an empty page.
overlay_render_region in modules/overlay/overlay.module
Renders an individual page region.
overlay_set_mode in modules/overlay/overlay.module
Sets the overlay mode and adds proper JavaScript and styles to the page.
overlay_set_regions_to_render in modules/overlay/overlay.module
Sets the regions of the page that rendering will be limited to.
overlay_store_rendered_content in modules/overlay/overlay.module
Stores strings representing rendered HTML content.
pager_get_query_parameters in includes/pager.inc
Compose a URL query parameter array for pager links.
path_get_admin_paths in includes/path.inc
Get a list of administrative and non-administrative paths.
path_is_admin in includes/path.inc
Determine whether a path is in the administrative section of the site.
search_dirty in modules/search/search.module
Marks a word as "dirty" (changed), or retrieves the list of dirty words.
search_get_info in modules/search/search.module
Returns information about available search modules.
search_index_split in modules/search/search.module
Simplifies and splits a string into tokens for indexing.
shortcut_current_displayed_set in modules/shortcut/shortcut.module
Returns the current displayed shortcut set for the provided user account.
simpletest_test_get_all in modules/simpletest/simpletest.module
Get a list of all of the tests provided by the system.
syslog_watchdog in modules/syslog/syslog.module
Implements hook_watchdog().
system_admin_menu_block in modules/system/system.module
Provide a single block on the administration overview page.
system_date_format_locale in modules/system/system.module
Gets the appropriate date format string for a date type and locale.
system_get_date_formats in modules/system/system.module
Gets the list of defined date formats and attributes.
system_get_date_types in modules/system/system.module
Gets the list of available date types and attributes.
system_get_module_admin_tasks in modules/system/system.module
Generate a list of tasks offered by a specified module.
system_list in includes/module.inc
Build a list of bootstrap modules and enabled modules and themes.
system_rebuild_module_data in modules/system/system.module
Rebuild, save, and return data about all currently available modules.
system_test_page_build in modules/simpletest/tests/system_test.module
Implements hook_page_build().
taxonomy_field_update in modules/taxonomy/taxonomy.module
Implements hook_field_update().
taxonomy_get_children in modules/taxonomy/taxonomy.module
Finds all children of a term ID.
taxonomy_get_parents in modules/taxonomy/taxonomy.module
Finds all parents of a given term ID.
taxonomy_get_parents_all in modules/taxonomy/taxonomy.module
Find all ancestors of a given term ID.
taxonomy_get_tree in modules/taxonomy/taxonomy.module
Create a hierarchical representation of a vocabulary.
taxonomy_vocabulary_get_names in modules/taxonomy/taxonomy.module
Get names for all taxonomy vocabularies.
template_preprocess in includes/theme.inc
Adds a default set of helper variables for variable processors and templates. This comes in before any other preprocess function which makes it possible to be used in default theme implementations (non-overridden theme functions).
template_preprocess_block in modules/block/block.module
Process variables for block.tpl.php
theme_comment_post_forbidden in modules/comment/comment.module
Returns HTML for a "you can't post comments" notice.
theme_get_setting in includes/theme.inc
Retrieve a setting for the current theme or for a given theme.
token_info in includes/token.inc
Returns metadata describing supported tokens.
toolbar_in_active_trail in modules/toolbar/toolbar.module
Checks whether an item is in the active trail.
translation_node_get_translations in modules/translation/translation.module
Get all nodes in a translation set, represented by $tnid.
update_get_projects in modules/update/update.compare.inc
Fetch an array of installed and enabled projects.
user_access in modules/user/user.module
Determine whether the user has a given privilege.
user_role_permissions in modules/user/user.module
Determine the permissions for one or more roles.
_block_compare in modules/block/block.admin.inc
Helper function for sorting blocks on admin/structure/block.
_drupal_build_css_path in includes/common.inc
Helper function for drupal_build_css_cache().
_drupal_session_read in includes/session.inc
Reads an entire session from the database (internal use only).
_drupal_session_write in includes/session.inc
Writes an entire session to the database (internal use only).
_field_sql_storage_query_field_conditions in modules/field/modules/field_sql_storage/field_sql_storage.module
Adds field (meta) conditions to the given query objects respecting groupings.
_form_options_flatten in includes/form.inc
Helper function for form_options_flatten().
_forum_user_last_visit in modules/forum/forum.module
_locale_import_one_string in includes/locale.inc
Imports a string into the database
_locale_translate_seek_query in includes/locale.inc
Build array out of search criteria specified in request variables
_menu_build_tree in includes/menu.inc
Build a menu tree.
_menu_clear_page_cache in includes/menu.inc
Helper function to clear the page and block caches at most twice per page load.
_menu_overview_tree_form in modules/menu/menu.admin.inc
Recursive helper function for menu_overview_form().
_menu_router_cache in includes/menu.inc
Helper function to store the menu router if we have it in memory.
_node_revision_access in modules/node/node.module
_node_types_build in modules/node/node.module
Builds and returns the list of available node types.
_openid_dh_rand in modules/openid/openid.inc
_openid_get_bytes in modules/openid/openid.inc
_rdf_get_default_mapping in modules/rdf/rdf.module
Helper function to get the default RDF mapping for a given entity type.
_trigger_get_all_info in modules/trigger/trigger.module
Retrieves and caches information from hook_trigger_info() implementations.
_update_create_fetch_task in modules/update/update.fetch.inc
Add a task to the queue for fetching release history data for a project.
_update_manager_cache_directory in modules/update/update.module
Return the directory where update archive files should be cached.
_update_manager_extract_directory in modules/update/update.module
Return the directory where update archive files should be extracted.
_update_manager_unique_identifier in modules/update/update.module
Return a short unique identifier for this Drupal installation.
_update_process_fetch_task in modules/update/update.fetch.inc
Process a task to fetch available update data for a single project.


includes/bootstrap.inc, line 3122

function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
  static $data = array(), $default = array();
  // First check if dealing with a previously defined static variable.
  if (isset($data[$name]) || array_key_exists($name, $data)) {
    // Non-NULL $name and both $data[$name] and $default[$name] statics exist.
    if ($reset) {
      // Reset pre-existing static variable to its default value.
      $data[$name] = $default[$name];
    return $data[$name];
  // Neither $data[$name] nor $default[$name] static variables exist.
  if (isset($name)) {
    if ($reset) {
      // Reset was called before a default is set and yet a variable must be
      // returned.
      return $data;
    // First call with new non-NULL $name. Initialize a new static variable.
    $default[$name] = $data[$name] = $default_value;
    return $data[$name];
  // Reset all: ($name == NULL). This needs to be done one at a time so that
  // references returned by earlier invocations of drupal_static() also get
  // reset.
  foreach ($default as $name => $value) {
    $data[$name] = $value;
  // As the function returns a reference, the return should always be a
  // variable.
  return $data;