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

How to pass a callback function with parameters for ob_start in PHP?

我一直在关注 this tutorial 缓存功能。我 运行 遇到了为 ob_start 传递回调函数 cache_page() 的问题。我如何将 cache_page() 与两个参数 $mid$path 一起传递给 ob_start,类似于

  ob_start("cache_page($mid,$path)");

以上当然不行。这是示例代码:

$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

signature of the callback to ob_start has to be:

string handler ( string $buffer [, int $phase ] )

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

cache_page($content, $p, $m)

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

在链接教程中,缓存文件名来自请求,例如

function cache_file()
{
    return CACHE_PATH . md5($_SERVER['REQUEST_URI']);
}

从您的代码来看,我认为您想手动定义文件路径。你可以做的是:

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

ob_start(function($buffer) use ($p, $m) {
    return cache_page($buffer, $p, $m);
});

这会将一个兼容的回调传递给 ob_start,它将使用输出缓冲区调用您的 cache_page 函数并将 closes over $p and $m 调用到回调中。