dongyuan1160 2011-08-15 20:11
浏览 136

while循环后函数中的静态变量

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 the 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?

  • 写回答

3条回答 默认 最新

  • douhuike3199 2011-08-15 20:14
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢