function countCalls() { static $calls = 0; // set static variable to 0 $calls++; // increment calls by 1 return $calls; // return the number of calls } echo countCalls(); // prints 1 echo countCalls(); // prints 2 echo countCalls(); // prints 3
function getCachedResult($id) { static $cache = array(); // set static cache to empty array if (isset($cache[$id])) { // check if result is already cached return $cache[$id]; // return cached result } else { $result = expensiveFunction($id); // calculate result $cache[$id] = $result; // cache result return $result; // return result } }In this example, we use a static array to cache the results of an expensive function call. The "getCachedResult" function first checks if the result for a given $id is already cached, and if so, returns the cached result. If the result is not cached, it calculates the result using the expensive function and caches the result in the static cache array before returning it. This way, the expensive function is only called once per $id. Both examples are part of the PHP core library.