输出缓冲,分层? [英] Output buffering, hierarchical?

查看:121
本文介绍了输出缓冲,分层?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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();
  回声< D​​IV CLASS =外>中;
  ob_start();
    回声< D​​IV CLASS =内>< / DIV>中;
  $内= ob_get_clean(); //< D​​IV CLASS =内>< / DIV>
  回声< / DIV>中;
$外= ob_get_clean(); //< D​​IV 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 matching ob_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆