Created
July 30, 2014 07:56
-
-
Save msankhala/332c1d98131c2cb0f83f to your computer and use it in GitHub Desktop.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment