When to use static php variables
If your a PHP developer this handy little variable can often be overlooked.
I’ve personally found quite a few situations which the static php variable comes in very handy, this is usually best used within a recursive function or within a static object that needs to retain it’s own config data between method calls. In this article I show you a nice way to implement the static variable to store data inside a function or method.
-
function config($var = '', $value = '')
-
{
-
static $config = array();
-
-
if(!empty($var) && !empty($value)):
-
$config[$var] = $value; /* set a new config value */
-
elseif(empty($value) && !empty($var)):
-
if(array_key_exists($var, $config)):
-
return $config[$var]; /* return a specific config value */
-
endif;
-
else:
-
return $config; /* return the entire config array */
-
endif;
-
-
return false;
-
}
-
?>
The above example is a simple function I use in my database class to save config data such as total database queries executed and connection data.
This function has 3 modes of operation. Notice the 3 blocks, if, elseif, else, each one of these performs a different function depending on how many arguments are passed.
Mode 1 Example
-
// set config value
-
config('welcometext', 'Hello World');
-
?>
The example above sets a new config value with the identifier ‘welcometext’ and value ‘Hello World’.
Mode 2 Example
-
// get config value
-
echo config('welcometext');
-
?>
This example simply fetches the config value we just set with the identifier ‘welcometext’.
Mode 3 Example
-
// get all config values
-
print_r(config());
-
?>
This last example returns the entire config array and in this case we use print_r() to dump the config to screen and see all keys and values in the config array.
