输出缓冲,分层? [英] Output buffering, hierarchical?
问题描述
在PHP输出缓冲的乐趣。它简化了很多东西。我用ob_start()在底部的脚本和ob_get_clean()(或任何其它功能)的顶部。
这两个电话之间是否有可能再次调用这些函数,而不干扰父的电话。
这是类型code的有效吗? (它工作得很好,但是......)这是一个良好的习惯?
< PHPob_start(); //注意 !!!回声'&所述p为H.;脚本&所述的顶部回声; / P>';
回声GetSomeOtherData(真);
回声'&所述p为H.; GetSomeOtherData()&所述后回波; / P>';$数据= ob_get_clean(); //注意 !!!
回声$的数据;//只是一个函数返回的东西,与输出缓冲的帮助
功能GetSomeOtherData($ toReturn)
{ ob_start(); //注意 !!!
呼应'< P>这已经被渲染功能&LT内部; / P>';
$ function_data = ob_get_clean(); //注意 !!! 如果($ toReturn ===真)
{
返回$ function_data;
}
其他
{
//可以是错误|返回别的东西
回归'< P>一种错误< / P>';
}
}
?>
从 ob_start()
手册:
输出缓冲区是可堆叠的,也就是说,你可以调用ob_start(),而
另一个ob_start()是有效的。只要确保你打电话
ob_end_flush()函数的适当次数。如果有多个输出
回调函数是活跃的,输出被依次过滤
通过嵌套为了他们每个人。
块引用>因此,它是完全有效的假设一个
OB_END / GET
将结束/返回匹配ob_start
例如:ob_start();
回声< DIV CLASS =外>中;
ob_start();
回声< DIV CLASS =内>< / DIV>中;
$内= ob_get_clean(); //< DIV CLASS =内>< / DIV>
回声< / DIV>中;
$外= ob_get_clean(); //< DIV CLASS =外>< / DIV>Output buffering in PHP is fun. It simplifies many things. I use ob_start() at the top of the script and ob_get_clean() (or any other function) at the bottom.
Between those two calls is it possible to call those functions again, without interfering the parent calls.
Is this type of code valid ? (it works fine, but...) Is this a good habit ?
<?php ob_start(); //NOTICE !!! echo '<p>echos of the top of the script</p>'; echo GetSomeOtherData(true); echo '<p>echos after GetSomeOtherData()</p>'; $data = ob_get_clean(); //NOTICE !!! echo $data; //just a function to return something, with the help of output buffering function GetSomeOtherData($toReturn) { ob_start(); //NOTICE !!! echo '<p>This has been rendered inside a function</p>'; $function_data = ob_get_clean(); //NOTICE !!! if($toReturn===true) { return $function_data; } else { //may be an error | return something else return '<p>An Error</p>'; } } ?>
解决方案From the
ob_start()
manual:Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.
So it is perfectly valid to assume that an
ob_end/get
will end/return the matchingob_start
e.g.:ob_start(); echo "<div class=outer>"; ob_start(); echo "<div class=inner></div>"; $inner = ob_get_clean(); // <div class=inner></div> echo "</div>"; $outer = ob_get_clean(); // <div class=outer></div>
这篇关于输出缓冲,分层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!