我修改了我的PHP代码,以避免在发现它表示编码模式不佳后使用输出缓冲。但仍然在不可避免地需要使用它。
但是,有些文章说使用输出缓冲是有益的,因为它将输出合并为一个,默认情况下输出分别分解为html和标题,然后显示在浏览器上,但输出缓冲消除了这个破坏过程,因此增加输出显示的速度给最终用户。
所有这些文章都让我处于两难境地,无法使用或完全避免输出缓冲。我不确定它是否完全正确的工作和我提到的要点。 所以请相应地指导我。
答案 0 :(得分:2)
有时使用输出缓冲是一件好事,但是要像许多人一样使用它( lazy 方式,例如在输出之前不必发送标头)现在不是时候。
你给出的例子,我不太了解,但如果它是最佳的,它可能是其使用的好时机之一。
它不被禁止使用ob_start()
,它只是" 错误的方式"按照我之前说的方式使用它。
您提到的优化感觉就像是一个非常低级别的优化,您可能会更快一点点“更快”。输出,但在标准的PHP脚本中通常有很多的其他优化,可以在值得关注之前加速它!
编辑: 在输出之前不使用发送标头的小脚本示例:
<?php
$doOutput = true;
$doRedirect = true;
$output = "";
if($doOutput == true){
// $doOutput is true, so output is supposed to be printed.
$output = "Some output yay!";
}
if($doRedirect == true){
// but $doRedirect is also true, so redirect will be done.
header("location:anotherpage.php"); // This will not produce an error cause there was no output!
exit();
}
// The echo below will not be printed in the example, cause the $doRedirect var was true.
echo $output;
而不是(这种情况会产生输出错误后发送的标头):
<?php
$doOutput = true;
$doRedirect = true;
if($doOutput == true){
//Output will be printed, cause $doOutput is true.
echo "Some output yay!";
}
if($doRedirect == true){
// but $doRedirect is also true, so redirect will be done.
header("location:anotherpage.php"); // This will produce an error cause output was already printed.
exit();
}
edit2:更新了一个更明显的例子!