How to avoid global variables in PHP

19 Jun 2020 21:09 | Geplaatst door Marcel |

In PHP variables are usually only available in the scope of a function or a class. For ‘easyness’ people sometimes (often?) revert to global variables. Variables can then become available in the global scope and can be pulled into any function where you might need it.

Problem is dat you might easily overwrite that variable. All you need is a typo like this:

function get_css_class( $post ) {
	global $variable;
	if ( $variable = 126 ) { // do something }
}

And only because you use the `=` for assigning a value to the variable you have now overwritten it, while you only wanted to test it with `==`.

A good way to not use global variables is to use static variables in a function that is both setter and getter. Like this function:

function get_css_class( $post ) {
	static $css_class_static;
	if ( $css_class_static ) {
		return $css_class_static;
	}
	$class = 'anything-i-want'; 
	$css_class_static = $class;
	return $css_class_static;
}

You can see here that if the variable `$css_class_static` was not set before, it gets assigned a value and saved as a static variable. The next time the function gets called, it is already set and it gets returned without having to calculate it again.
This function is both a setter (first time it’s called) and a getter (anytime it is called).
The advantage is that your variable is not in the global scope and is thus modularized and not easily overwritten.
Do pay attention to the fact that this static variable only exists during the same request, just like any global variable.

If you are using WordPress and want to go one step further you can even use the cache by using the `wp_cache_add()` and `wp_cache_get()` functions. Make sure to use keys that are unique to that data.
Also be aware that in most setups this data will only exist during the same request. Be sure to test this though, software like Memcached and Redis might be involved that make cache data survive requests.
Most software systems will have a cache system like this, and you might want to look into it.