2014-03-19 41 views
0

我爲我的網站創建了一個簡單的緩存系統,但我遇到了一個奇怪的問題。當我在ob_start之後立即致電call_user_func時,它沒有被正確捕獲並停止執行。ob_start和call_user_func不能一起工作

這裏是我的緩存類代碼:

<?php 

class Cache 
{ 
    public static function caching($name, $callback, $duration = 120, $debug = true) 
    { 
     if ($debug) $start_time = microtime(true); 

     // Compute file name 
     $cache = 'cache' . DIRECTORY_SEPARATOR . $name .'_' . md5(join('-', $_POST)) . '.cache'; 
     $expire = time() - $duration; 

     if(file_exists($cache)) 
     { 
      if (filemtime($cache) > $expire) 
      { 
       // Display content saved into the cache file 
       readfile($cache); 
       if ($debug) echo '<br />' . (microtime(true) - $start_time * 1000) . 'microseconds'; 
       return; 
      } 
      else 
      { 
       // File is too old so we can delete it 
       unlink($cache); 
      } 
     } 

     // Init buffer 
     ob_start(); 

     // Do job 
     if (function_exists($callback)) call_user_func($callback); 
     else echo 'Function ' .$callback. ' doesn\'t exist.'; 

     // Retrieve buffer 
     $page = ob_get_contents(); 
     ob_end_clean(); 

     // Save buffer to a cache file 
     file_put_contents($cache, $page); 

     // Display content 
     echo $page; 

     if ($debug) echo '<br />' . (microtime(true) - $start_time * 1000) . 'microseconds'; 
    } 
} 

這裏是我的樣本代碼:

<?php 

require('cache.class.php'); 

function run() 
{ 
    if (isset($_GET['sid'])) 
    { 
     $sid = htmlentities($_GET['sid']); 
     echo 'sid is ' . $sid; 
    } 
} 

Cache::caching('Sample', 'run'); 
die(); 

,使其顯示sid id XXXXX當它被調用,但它不走的更遠方法caching。行$page = ob_get_contents();永遠不會到達,我沒有任何錯誤消息。

我使用ob_startcall_user_fun兩種方法做錯了什麼,或者這是一個真正的問題嗎?

+0

你確定你的整個'Caching'函數不會停在'return;'行嗎? – Tularis

+0

是的,我完全肯定。我在這條線上放了一個'echo',它從來沒有被調用過。 – Manitoba

+0

你打開error_reporting/display_errors了嗎?你永遠不應該首先開發/測試/調試它們。 –

回答

0

要回答我的問題:

顯然,這是一個已知的問題PHP 5.2。我已要求我的託管服務將其更新至5.4,問題已解決。