Statics and globals

WordPress has a known global variables problem. We use them way too much. People try to mitigate this bad practice by using static variables instead of globals, since there are plenty of situations where a static will work just as well.

It can be tricky to grasp the distinction between static and global variables, but this is the best explanation I’ve found so far.

The lexical scope of a static static variable is restricted to the function body – you cannot access the variable outside the function. However, its value will be remembered across multiple calls of the same function.

Global variables exist in global scope and can be accessed from anywhere in your code (you have to use the global keyword or $GLOBALS array inside functions though)

knittl on StackOverflow

This is a great example of where you might use a static. fm_calculate_context(); is performance-intensive, but the result, $calculated_context, is used often.

Instead of polluting the $GLOBALS array, the static keeps the calculated value safe and available in fm_get_context(), and it doesn’t have to be recalculated each time.

function fm_get_context( $recalculate = false ) {
	static $calculated_context;
	if ( ! $recalculate && $calculated_context ) {
		return $calculated_context;
	} else {
		$calculated_context = fm_calculate_context();
		return $calculated_context;
	}
}

Context

Advertisements