Provides 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 (!isset($languages[$field])) {
...
}
return $languages[$field];
}
function locale_translate_overview_screen() {
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(...) {
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(). 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:
<?php
$foo = &drupal_static(__FUNCTION__);
?>
with:
<?php
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.
- http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static
- http://php.net/manual/en/language.variables.scope.php#language.variables.scope.references
The example below shows the syntax needed to work around both limitations.
For benchmarks and more information, see http://drupal.org/node/619666.
Example:
<?php
function user_access($string, $account = NULL) {
static $drupal_static_fast;
if (!isset($drupal_static_fast)) {
$drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
}
$perm = &$drupal_static_fast['perm'];
...
}
?>
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.
See also
drupal_static_reset()
- 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
- Loads an aggregator category.
- aggregator_feed_load in modules/aggregator/aggregator.module
- Loads an aggregator feed.
- archiver_get_info in includes/common.inc
- Retrieves a list of all available archivers.
- arg in includes/bootstrap.inc
- Returns 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
- Returns 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
- Adds a feed URL for the current page.
- drupal_add_html_head in includes/common.inc
- Adds output to the HEAD tag of the HTML page.
- drupal_add_http_header in includes/bootstrap.inc
- Sets 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
- Assists 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
- Prepares a 'destination' URL query parameter for use with drupal_goto().
- drupal_get_filetransfer_info in includes/common.inc
- Assembles the Drupal FileTransfer registry.
- drupal_get_http_header in includes/bootstrap.inc
- Gets 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
- Assembles the Drupal Updater registry.
- drupal_html_id in includes/common.inc
- Prepares a string for use as a valid HTML ID and guarantees 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
- Sets HTTP headers in preparation for a page response.
- drupal_page_is_cacheable in includes/bootstrap.inc
- Determines 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
- Collects #attached for an element and its children 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
- Sends the HTTP response headers that were previously set, adding defaults.
- drupal_set_breadcrumb in includes/common.inc
- Sets the breadcrumb trail for the current page.
- drupal_set_page_content in includes/common.inc
- Sets the main page content value for later use.
- drupal_set_title in includes/bootstrap.inc
- Sets the title of the current page.
- drupal_static_reset in includes/bootstrap.inc
- Resets 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
- Retrieves 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
- Returns an array of field_type options.
- field_ui_formatter_options in modules/field_ui/field_ui.admin.inc
- Returns an array of formatter options for a field type.
- field_ui_widget_type_options in modules/field_ui/field_ui.admin.inc
- Returns 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
- Retrieves 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
- Returns the IP address of the client machine.
- language_fallback_get_candidates in includes/language.inc
- Return the possible fallback languages ordered by language weight.
- language_list in includes/bootstrap.inc
- Returns a list of installed languages, 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_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
- Processes 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
- Sorts active blocks by region, then by weight; sorts inactive blocks by name.
- _drupal_build_css_path in includes/common.inc
- Prefixes all paths within a CSS file 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.
File
- includes/bootstrap.inc, line 3201
- Functions that need to be loaded on every Drupal request.
Code
<?php
function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
static $data = array(), $default = array();
if (isset($data[$name]) || array_key_exists($name, $data)) {
if ($reset) {
$data[$name] = $default[$name];
}
return $data[$name];
}
if (isset($name)) {
if ($reset) {
return $data;
}
$default[$name] = $data[$name] = $default_value;
return $data[$name];
}
foreach ($default as $name => $value) {
$data[$name] = $value;
}
return $data;
}
?>
Login or
register to post comments
Comments
Good intro to using drupal_static for caching
Here is a good introduction to drupal_static as it relates to caching in D7 from Jeff Eaton here:
http://www.lullabot.com/articles/beginners-guide-caching-data-drupal-7