2012-08-05 75 views
3

我有一个从数据库运行查询的功能。然后,它将被另外两个函数调用。不止一次从函数中获取结果可能会导致此函数再次执行查询?

function query(){ 
$query= // get data from database; 
return $query; 
} 

function show_something(){ 
$data = query(); 
//do something 
} 

function show_else(){ 
$data = query(); 
//do something else 
} 

函数query()被调用两次。我想它会在每次调用该函数时执行查询作业,除非结果被缓存。如果我错了,有人会纠正我吗?

回答

0

你可以简单地做这样的事情:

  • 设置的指示标记,如果查询是第一次或多次。
  • 查询前,检查指标。

代码:

$fresh = true; // fresh results wanted 
function query(){ 
global $fresh; 
if($fresh){ 
    $query= // get data from database; 
    $bar = $query; // cache the $query value for next uses.. 
    $$fresh = false; // set the indicator that query is cached. 
}else{ // this is repeated query 
    $query = $bar; //we had set the $bar last time 
} 
return $query; 
} 

function show_something(){ 
//first time query, $query will be fetched from database, 
// also $fresh will be set to false 
$data = query(); 
//do something 
} 

function show_else(){ 
//repeated query, cached value will be returned. 
$data = query(); 
//do something else 
} 

$foo = true; // if you want fresh results, set $fresh to true before query 
function show_fresh(){ 
//results will be fresh, because we have set $fresh to true again. 
$data = query(); 
//do something else 
} 
+0

感谢您的详细代码! – Jenny 2012-08-05 09:07:42

+0

很高兴帮助..不客气.. – DavChana 2012-08-05 09:09:41

3

是的,它会被调用两次。如果需要,可以使用静态变量来缓存结果。

0

不,这是正确的;你的函数无条件地执行显式查询,因此每次调用它都会执行它。

0

数据库可能在函数调用之间发生了变化。即使他们立即被一个接一个地打电话。

所以,是的,查询将运行两次;因为结果可能会有所不同。

除非你实现了一些缓存机制。

2

如果你每次都期待相同的查询被牵拉(即没有变量的变化),你可能会更好使用沿着这些线路的对象:

class checkSomethingOrOther 
{ 
    public $myVariable; 

    public function __get($name) 
    { 
     if (!array_key_exists($name, $this->myVariable)) 
     { 
      $this->myVariable=query(); 
     } 
     return $this-myVariable; 
    } 
} 

这将简单地检查,看是否变量被设置,如果没有,它抓取数据并返回它,否则,只是返回它。

+0

我明白了。这样每次都可以避免数据库调用。谢谢! – Jenny 2012-08-05 09:01:30