As nice as event-driven programming can be within the context of WordPress’ hook system, one of the challenges is preventing code from executing every single time the hook is called.
For example, say you’re writing a function that fires during the init
action but something happens in WordPress core that triggers the init
action to fire again consequently causing your code to fire once again even though it’s unneeded.
Multiply this across however many callbacks spread across however many files and general functionality registered with the hook and you may end up affecting performance and/or executing code that has no need to be run.
Static Variables in Plugin Bootstrap Files
One way this can happen is in a plugin’s bootstrap. Case in point: Say your plugin is registered with the init
action and then it sets up a registry which in turn instantiates a set of subscribers that register services. Repeating this every single time init
is fired is unnecessary.
Here’s a way to manage this:
add_action( 'init', 'tm_acme_function', 100);
function tm_acme_function() {
static $initialized = false;
if ( $initialized ) {
return;
}
$initialized = true;
// ... set up the rest of the function.
}
If you know how static variables work, you’re may already be doing this, you’re able to follow the above code, or both. And if that’s the case, there’s nothing else to see here.
But if not, static
variables can be useful in this scenario because static
variables maintain state between calls whereas regular variables are reinitialized every time the function fires. This means a static
variable retains its value across multiple calls to the function.
Static Variables and Plugins
So having an static $initialized
flag works like this:
$initialized
starts asfalse
.- When the function runs for the first time, the
$initialized
variable is set totrue
. - On subsequent calls, the condition
if ( $initialized )
prevents the rest of the function from executing, effectively short-circuiting it.
And because of that, this:
- prevents redundant execution,
- optimizes performance by avoiding running unnecessary code (especially as it relates to registering duplicate functionality, running multiple queries, or trashing data unintentionally).
If your plugin’s bootstrap registers a callback with a WordPress hook, considering using static variables to prevent code from being called unnecessarily more than once.