如何在PHP中传递带有ob_start参数的回调函数?

Red*_*ant 4 php caching ob-start

我一直在关注这个教程上的缓存功能.我遇到了传递回调函数cache_page()的问题ob_start.如何传递cache_page()沿两个paramters $mid$pathob_start,沿东西线

  ob_start("cache_page($mid,$path)");
Run Code Online (Sandbox Code Playgroud)

当然以上都行不通.这是示例代码:

$mid = $_GET['mid'];

$path = "cacheFile";

define('CACHE_TIME', 12);

function cache_file($p,$m)
{
    return "directory/{$p}/{$m}.html";
}

function cache_display($p,$m)
{
    $file = cache_file($p,$m);

    // check that cache file exists and is not too old
    if(!file_exists($file)) return;

    if(filemtime($file) < time() - CACHE_TIME * 3600) return;

    header('Content-Encoding: gzip');

    // if so, display cache file and stop processing
    echo gzuncompress(file_get_contents($file));

    exit;
}

  // write to cache file
function cache_page($content,$p,$m)
{
  if(false !== ($f = @fopen(cache_file($p,$m), 'w'))) {
      fwrite($f, gzcompress($content)); 
      fclose($f);
  }
  return $content;
}

cache_display($path,$mid);

ob_start("cache_page"); ///// here's the problem
Run Code Online (Sandbox Code Playgroud)

Gor*_*don 5

回调ob_start签名必须是:

string handler ( string $buffer [, int $phase ] )
Run Code Online (Sandbox Code Playgroud)

您的cache_page方法具有不兼容的签名:

cache_page($content, $p, $m)
Run Code Online (Sandbox Code Playgroud)

这意味着您期望不同的参数($p$m)ob_start将传递给回调.没有办法ob_start改变这种行为.它不会发送$p$m.

在链接教程中,缓存文件名是从请求派生的,例如

function cache_file()
{
    return CACHE_PATH . md5($_SERVER['REQUEST_URI']);
}
Run Code Online (Sandbox Code Playgroud)

从您的代码我想要手动定义文件路径.那你可以做的是:

$p = 'cache';
$m = 'foo';

ob_start(function($buffer) use ($p, $m) {
    return cache_page($buffer, $p, $m);
});
Run Code Online (Sandbox Code Playgroud)

这会传递一个兼容的回调ob_start,它将cache_page使用输出缓冲区调用您的函数并关闭$p$m进入回调.