如何在PHP中使用ob_start的参数传递回调函数?
问题描述:
我一直在关注缓存功能this tutorial。我遇到了为ob_start
传递回调函数cache_page()
的问题。如何传递cache_page()
两个paramters $mid
和$path
一起ob_start
,沿如何在PHP中使用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
步入回调。
你能否澄清一下'cache_page'函数应该做些什么?我发现它需要三个参数,但你只在'ob_start'调用中传递两个参数。同样,'ob_start'的回调函数必须有签名'string handler(string $ buffer [,int $ phase])' – Gordon