Often you'll create some utility functions that are called incessantly to only return the same result every time during a request. Although not a feature of Drupal itself, harnessing the power of PHP static variables can do for your code's performance.
Example #1 (simple, PHP method)
<?php
function i_get_called_way_too_much() {
static $static_var;
if (!isset($static_var)) {
// generate contents of static variable
$static_var = 'some value';
}
return $static_var;
}
?>Drupal 7 includes a new way to store and use static variables. The new method drupal_static(), providing a centralized function, allows other module to dynamically reset these variables. In a normal PHP implementation, only the function in which the variable is in scope could do this.
Example #2 (Drupal 7 method)
<?php
function i_get_called_way_too_much() {
$var = &drupal_static(__FUNCTION__);
if (!isset($var)) {
// generate contents of static variable
$var = 'some value';
}
return $var;
}
// allows for static variables to be reset from another function
drupal_static_reset('i_get_called_way_too_much');
?>

Comments
Thanks!
Submitted by Juonio on
Just the thing I needed to know. Thanks for sharing the knowledge!
Glad to hear it helped! This
Submitted by erikwebb on
Glad to hear it helped! This is exactly why I put together this presentation - too many goodies hidden in Drupal core than most developers never know about.
it help me a lot,thanks
Submitted by tony on
it help me a lot,thanks
$reset mention
Submitted by Todd Painton on
Thanks. Might also mention using a $reset = FALSE parameter. That way, you can set it up so the variable doesn't always have to be static.
Add new comment