2012-08-05 76 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