drupal_static

Versions
7
&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.

Example:

<?php

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.
  drupal_static_reset('language_list');
...
}

?>

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.

Example:

<?php

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

?>

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(). For benchmarks and background on this variant, please see http://drupal.org/node/619666.

Example:

<?php

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

?>

See also

drupal_static_reset()

Parameters

$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.

▾ 139 functions call drupal_static()

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.
ajax_process_form in includes/ajax.inc
Add AJAX information about a form element to the page to communicate with JavaScript.
archiver_get_info in includes/common.inc
Retrieve a list of all available archivers.
arg in includes/path.inc
Return a component of the current Drupal path.
block_admin_display in modules/block/block.admin.inc
Menu callback for admin/structure/block.
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.
comment_num_replies in modules/comment/comment.module
Get replies count for a comment.
conf_path in includes/bootstrap.inc
Find the appropriate configuration directory.
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
Add 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/common.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_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_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
Determine 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/path.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_build_modes in modules/field/field.module
Registry of available build modes.
field_extra_fields in modules/field/field.module
Registry of pseudo-field components in a given bundle.
field_multilingual_available_languages in modules/field/field.multilingual.inc
Collect the available languages for the given entity type and field.
field_test_entity_info_translatable in modules/field/tests/field_test.module
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_build_modes_tabs in modules/field_ui/field_ui.module
Group available build modes on tabs on the 'Manage display' page.
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.
file_get_file_references in modules/file/file.module
Get 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.
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.
fix_gpc_magic in includes/common.inc
Fix double-escaping problems caused by "magic quotes" in some PHP installations.
format_date in includes/common.inc
Format a date with the given configured format or a custom format string.
form_set_error in includes/form.inc
File an error against a form element.
forum_field_storage_pre_update in modules/forum/forum.module
Implement hook_field_storage_pre_update().
hook_field_storage_pre_update in modules/field/field.api.php
Act before the storage backends update field data.
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. If Drupal is run in a cluster we use 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
Create an array of allowed values for this field.
list_field_create_field in modules/field/modules/list/list.module
Implement hook_field_create_field().
list_field_update_field in modules/field/modules/list/list.module
Implement hook_field_update_field().
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_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 or gets the active trail (path to root menu root) of the current page.
menu_tree in includes/menu.inc
Render 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.
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.
pager_get_query_parameters in includes/pager.inc
Compose a URL query parameter array for pager links.
search_get_info in modules/search/search.module
Get information about all available search hooks.
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.
simpletest_verbose in modules/simpletest/drupal_web_test_case.php
Log verbose message in a text file.
syslog_watchdog in modules/syslog/syslog.module
Implement 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
Get the appropriate date format for a type and locale.
system_get_date_formats in modules/system/system.module
Get the list of date formats for a particular format length.
system_get_date_types in modules/system/system.module
Get 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_region_list in modules/system/system.module
Get a list of available regions from a specified theme.
system_test_page_build in modules/simpletest/tests/system_test.module
Implement hook_page_build().
taxonomy_field_update in modules/taxonomy/taxonomy.module
Implement hook_field_update().
taxonomy_get_tree in modules/taxonomy/taxonomy.module
Create a hierarchical representation of a vocabulary.
template_preprocess_block in modules/block/block.module
Process variables for block.tpl.php
theme_comment_post_forbidden in modules/comment/comment.module
Theme 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.
url in includes/common.inc
Generate a URL.
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_bootstrap_full in includes/common.inc
_drupal_build_css_path in includes/common.inc
Helper function for drupal_build_css_cache().
_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
_lock_id in includes/lock.inc
Helper function to get this request's unique id.
_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
Returns the default RDF mapping for a given entity type.
_system_rebuild_theme_data in modules/system/system.module
Helper function to scan and collect theme .info data and their engines.
_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_extract_directory in modules/update/update.manager.inc
Return the directory where update archive files should be extracted.
_update_process_fetch_task in modules/update/update.fetch.inc
Process a task to fetch available update data for a single project.

Code

includes/bootstrap.inc, line 2189

<?php
function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
  static $data = array(), $default = array();
  if (!isset($name)) {
    // All variables are reset. 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;
  }
  if ($reset) {
    // The reset means the default is loaded.
    if (array_key_exists($name, $default)) {
      $data[$name] = $default[$name];
    }
    else {
      // Reset was called before a default is set and yet a variable must be
      // returned.
      return $data;
    }
  }
  elseif (!array_key_exists($name, $data)) {
    // Store the default value internally and also copy it to the reference to
    // be returned.
    $default[$name] = $data[$name] = $default_value;
  }
  return $data[$name];
}
?>
Login or register to post comments
 
 

All source code and documentation on this site is released under the terms of the GNU General Public License, version 2 and later. Drupal is a registered trademark of Dries Buytaert.