PHP – how to use function static variable as cache

PHP function static variable exists only in a local function scope but it does not lose its value after function execution. It can be used as cache for things like memcache lookup, etc. Here is php code snippet showing function static variable behaviour.

<?php
$v = get_val();
$v = get_val();
$v = get_val();
function get_val() {
  static $cached_val = null;
  if ($cached_val === null) {
    echo "cached_val is null\n";
    $cached_val = get_val_expensive();
  } else {
    echo "cached_val is not null. reusing it.\n";
  }
  return $cached_val;
}
function get_val_expensive() {
  echo "In get_val_expensive()\n";
  return 100;
}
?>
cached_val is null
In get_val_expensive()
cached_val is not null. reusing it.
cached_val is not null. reusing it.
Env: PHP 5.5.9 (Linux)

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments