开发者

Static Variables in Function after while loop

I have a database abstraction layer in a CMS, and one of the functions is a mysql_fetch_assoc wrapper which includes the connection, query and result logic all in one.

_select_row($in_table, $in_what = '*', $in_where = '', 
            $in_arr_params = array(), $in_flags)
{
  // Generates a unique enough name based on query contents.
  $hash = md5($in_table.$in_what.implode((array)$in_arr_params).$in_flags);

  if (!isset($_STATIC))
  {
    static $_STATIC = array();
  }

  if (isset($_STATIC[$hash])
  {
    return mysql_fetch_assoc($_STATIC[$hash]);
  }

  // *snip* SQL logic here, connect -> query -> result *snip*

  $_STATIC[$hash] = $result;
  return mysql_fetch_assoc($_STATIC[$hash]);
}

It maintains a static variable so when being used in loops, it can iterate like a standard fetch_assoc call.

while (_select_row('mytable')) // Loops all rows
{
  // Do Stuff
}

The only problem I'm having is a corner case: if the programmer tries to make the same query again later in the script, it will continue the iteration instead of starting again. I could create a reset function of some sort, or work with a selector function and a results function, but I was hoping for a more elegant solution in which t开发者_如何学编程he function would "know" when it was not being called in the same loop, and dump the results. Also, just for efficiency sake I'd like it to dump results when they are done.

Any ideas, or is switching to a select->result model really the only way around this?


Statics are generally a bad idea, for exactly this sort of reason.

Just pass in an extra parameter, as a reference to a "state" structure that's updated by the function on each iteration.

If you want to get advanced, you could wrap the function in a class, that maintains the state.


You can add a boolean reset flag to the function to indicate if it is to reset:

_select_row($in_table, /* snip a bunch of params */, $reset=FALSE)
{
  // Generates a unique enough name based on query contents.
  $hash = md5($in_table.$in_what.implode((array)$in_arr_params).$in_flags);

  if (!isset($_STATIC))
  {
    static $_STATIC = array();
  }

  if (isset($_STATIC[$hash])
  {
    return mysql_fetch_assoc($_STATIC[$hash]);
  }

  // *snip* SQL logic here, connect -> query -> result *snip*

  $_STATIC[$hash] = $result;
  ////////////////////////////////////////////////////
  // If this is a reset, set position to 0
  if ($reset) mysql_data_seek($_STATIC[$hash], 0);
  ////////////////////////////////////////////////////

  return mysql_fetch_assoc($_STATIC[$hash]);
}


I know you wanted elegant, but you could use debug_backtrace() to figure out where this was called from.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜