Informatika Mihelac
May 13 2008 drupal | php | static variables

Static variables and unset()

In Drupal many things are cached with static variables and this is often main source of headache. I just submitted small patch for bug where static cache does not work as it should. Bug report and this example shows that unset() should not be used with static variables:

<?php
function locale_supported_languages($reset = FALSE, $val = array()) {
  static $all = NULL;

  if ($reset) {
    // If a static variable is unset() inside of a function, unset() destroys the variable only in the context of the rest of a function. Following calls will restore the previous value of a variable.
    unset($all); // this would not work
    //$all = NULL; // this would work
  }

  if (is_null($all)) {
    $all = array();
    foreach ($val as $key => $value) {
      $all[$key] = $value;
    }
  }
  return $all;  
}

echo "\narray should have 'cached' element (PASS):";
print_r(locale_supported_languages(FALSE, array("first" => "cached")));

echo "\narray should have 'new' element (PASS):";
print_r(locale_supported_languages(TRUE, array("first" => "new")));

echo "\narray should have 'new' element but have 'cached' (FAILS):";
print_r(locale_supported_languages(FALSE));

About

I am Bojan Mihelac and this blog is dedicated to share code, thoughts, tools and advices I came up with while working in Informatika Mihelac.

Contact: bmihelac@mihelac.org

RSS feedSubscribe to RSS Feed