For example:
<?php
function get_current_user_id(){
static $id;
if(!$id){
$id = 5;
echo "Id set.";
}
return $id;
}
$id = get_current_user_id();
$id2 = get_current_user_id();
$id3 = get_current_user_id();
echo "IDs: ".$id." ".$id2." ".$id3;
?>
//Output:
Id set.IDs: 5 5 5
Thus presumably repeated calls to get the user id just do a simple return of an id still in memory. I don’t know if this is idiomatic use of php functions, though. It’s kinda like a singleton, except not OO, and I’ve never heard of or seen other people using it, so I’m wondering if there are downsides to using statics in this manner, or if there are gotchas I should be aware of for more complex use cases of statics in functions.
So, what problems might I encounter with this type of usage of statics?
I don’t think there is anything wrong with that approach — actually, I use it myself quite often, as a “very short-lifetime caching mecanism“, which is great/useful when you have a function that is called a lot of times, and does heavy calculations (like a database query) to always return the same value for a given execution of a script.
And I know I’m not the only one doing this : Drupal, for instance, uses this mecanism a lot — as a cache, too.
The only “problem” I see is when you want to “clear the cache” : you have to pass an additionnal parameter to the function ; and code a couple of lines to “reset” the static cache when that parameter is set.