为什么多次调用缓冲区时不输出任何内容?

问题描述:

我有一个名为test.php的PHP文件,其中包含以下代码。为什么多次调用缓冲区时不输出任何内容?

<?php 
$text = 'Grrrrr'; 
ob_start(); 
require_once('testinc.php'); 
$html2 = ob_get_clean(); 
echo '<pre>'; 
var_dump($html2); 
echo '</pre>'; 


$text = 'wtf'; 
ob_start(); 
require_once('testinc.php'); 
$html2 = ob_get_clean(); 
echo '<pre>'; 
var_dump($html2); 
echo '</pre>'; 


testing('blah'); 
testing('123'); 

function testing($text) { 
    ob_start(); 
    require_once('testinc.php'); 
    $html = ob_get_clean(); 
    echo '<pre>'; 
    var_dump($html); 
    echo '</pre>'; 
} 

testinc.php文件包含以下代码。

<?php 
echo $text; 
?> 
testing 

当我运行代码时,输​​出如下所示。

string(13) "Grrrrrtesting" 
string(0) "" 
string(0) "" 
string(0) "" 

为什么不大于第一次工作缓冲区等,我怎样才能输出到这个样子?

string(13) "Grrrrrtesting" 
string(10) "wtftesting" 
string(11) "blahtesting" 
string(10) "123testing" 
+1

您是否阅读过ob_get_clean和require_ONCE的文档? –

+0

真的吗?!将require_once()更改为include()可以解决所有问题。使用大量输出缓冲的 – Casey

+0

通常意味着您的代码结构错误 – nogad

解决方案是不使用require_once()。将代码更改为包含(),并且它一切正常。