只是为了稍微澄清一下Ninsuo的正确答案。
我的两个代码示例实际上不会产生相同的结果。事实上,结合使用回调ob_get_clean()
是完全没用的。
这是因为在清理或刷新缓冲区时应用了回调。
但是ob_get_clean()
首先检索内容,然后清理缓冲区。这意味着返回的内容不是回调返回的结果,而是传递给回调的输入。
我写了这两个简单(和hacky)的脚本来演示。
这个使用ob_get_clean()
并不会产生正确的结果:
// Tests the use of callbacks with ob_get_clean().
class TestWithGetClean {
// This variable is set when obcallback is called.
public $foo = null;
// The output buffer callback.
public function obcallback($value) {
$this->foo = 'set';
return $value . '(modified)';
}
// Main method.
public function run() {
ob_start(array($this, 'obcallback'));
echo 'this is the output', PHP_EOL;
return ob_get_clean();
}
}
// Run the test with ob_get_clean().
$t = new TestWithGetClean();
echo $t->run(); // This method returns a value in this test. (But not the correct value!)
echo $t->foo, PHP_EOL;
运行它的输出是:
这是输出
放
文本'(modified)'
不会出现在任何地方。但是请注意,实例变量$foo
已设置,因此肯定会调用回调,但是输出与我最初预期的不同。
与使用的这个比较ob_end_flush()
:
// Tests the use of callbacks with ob_end_flush().
class TestWithEndFlush {
// This variable is set when obcallback is called.
public $foo = null;
// The output buffer callback.
public function obcallback($value) {
$this->foo = 'set';
return $value . '(modified)' . PHP_EOL;
}
// Main method.
public function run() {
ob_start(array($this, 'obcallback'));
echo 'this is the output', PHP_EOL;
ob_end_flush();
}
}
// Run the test with ob_end_flush().
$t2 = new TestWithEndFlush();
$t2->run(); // This method produces output in this test.
echo $t2->foo, PHP_EOL;
这个产生以下输出:
这是输出
(修改的)
放
但是,这当然没有那么有用,因为输出直接发送到客户端,因此我们无法进一步操纵结果。(例如,将文本包装在 Symfony HttpFoundation 组件请求对象中)。