Apr 12 2013

Howto Reset PHP Static Variable

Category: #apache,#howto,#linux,#networking,#root,#ubuntu-server —  Juan @ 13:21 
 

Today, I spent about an hour trying to figure out how to clear [or reset] a PHP static variable. PHP static variables do not do what you may initially think. PHP static variables do not carry over from page to page as $_SESSION does.

In any case, take the following function as example:

Kode  
function get_config_option($option)
{  
   static $local;
   global $db;

   if ((count($local) == 0) || !is_array($local))
   {
      $local   = array();
      $sql  = "SELECT option_name, option_value FROM some_table";
      $result  = $db->sql_query($sql);

      while ($row = $db->sql_fetchrow($result))
      {
         $local[$row['ab_option_name']] = trim(stripslashes($row['ab_option_value']));
      }
   }

   return $local[$option];
}

During the course of a single page load, the variable $local persists and, as such, each time the function is called, it queries the database only the first very time. This is an one example that can be considered lazy loading of data.

At some point, I ran into a situation where I needed to clear out, or unset, the static variable. The secret here is to clear the variable after the function re-declares the static variable, as such:

Kode  
function get_config_option($option)
{  
   static $local;
   global $db;

   if (is_integer($option) && ($option == DOUCHE_OPTIONS))
   {
      $local = NULL;
      return;
   }

   if ((count($local) == 0) || !is_array($local))
   {
      $local   = array();
      $sql  = "SELECT option_name, option_value FROM some_table";
      $result  = $db->sql_query($sql);

      while ($row = $db->sql_fetchrow($result))
      {
         $local[$row['ab_option_name']] = trim(stripslashes($row['ab_option_value']));
      }
   }

   return $local[$option];
}

I created a recognizable constant so that the function will not treat it like an option query. In my example, I defined the following constant (in an external “included” script):

Kode  
define('DOUCHE_OPTIONS', 420);

Yes, I have a sense of humor when it comes to coding.

 

Tags: , , ,

One Response to “Howto Reset PHP Static Variable”

  1. dvb t says:
     

    As a Newbie, I am continuously searching online for articles that can aid me. Thank you

Leave a Reply