gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 22:53:43 24 4
gpt4 key购买 nike

我一直在关注 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,它将使用输出缓冲区和 closes over $p and $m 调用您的 cache_page 函数进入回调。

关于php - 如何在 PHP 中为 ob_start 传递带参数的回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29861852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com