【问题标题】:How to pass a callback function with parameters for ob_start in PHP?如何在 PHP 中传递带有 ob_start 参数的回调函数?
【发布时间】:2015-04-25 06:32:57
【问题描述】:

我一直在关注 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

【问题讨论】:

  • 你能澄清一下cache_pagefunction 应该做什么吗?我看到它需要三个参数,但您只在 ob_start 调用中传递了两个参数。同样,ob_start 的回调必须具有签名 string handler ( string $buffer [, int $phase ] )

标签: php caching ob-start


【解决方案1】:

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,它将使用输出缓冲区和closes over $p and $m 调用您的cache_page 函数到回调中。

【讨论】:

  • 我们应该能够投票解释和澄清
猜你喜欢
  • 1970-01-01
  • 2019-06-10
  • 2015-08-29
  • 2022-01-12
  • 2018-11-19
  • 2012-12-21
  • 2014-09-03
  • 1970-01-01
  • 2021-02-08
相关资源
最近更新 更多