首页  >  文章  >  后端开发  >  PHP嵌套输出缓存实例

PHP嵌套输出缓存实例

*文
*文原创
2017-12-26 15:18:001066浏览

PHP如何实现嵌套输出缓存?本文主要介绍了PHP嵌套输出缓存代码实例,使用ob系列函数来解决嵌套输出缓存的实例。希望对大家有所帮助。

PHP的输出缓存是可以嵌套的。用ob_get_level()就可以输出嵌套级别。
测试发现在cli和浏览器下输出结果不一样(PHP5.4)。

手册说明如下:

ob_get_level() will always return 0 inside a destructor. 
This happens because the garbage collection for output buffers has already done before the destructor is called

想要正确输出也很简单:

ob_end_clean();
echo ob_get_level(); //0

回到正题:

ob_end_clean();
 
ob_start();
echo 'php1';//此处并不会在页面中输出
$a = ob_get_level();
$b = ob_get_contents();//获得缓存结果,赋予变量
ob_clean();
 
ob_start();
echo 'php2';//此处并不会在页面中输出
$c = ob_get_level();
$d = ob_get_contents();//获得缓存结果,赋予变量
ob_clean();
 
ob_start();
echo 'php3';//此处并不会在页面中输出
$e = ob_get_level();
$f = ob_get_contents();//获得缓存结果,赋予变量
ob_clean();
 
echo &#39;level:&#39;.$a.&#39;,ouput:&#39;.$b.&#39;<br>&#39;;
echo &#39;level:&#39;.$c.&#39;,ouput:&#39;.$d.&#39;<br>&#39;;
echo &#39;level:&#39;.$e.&#39;,ouput:&#39;.$f.&#39;<br>&#39;;

结果如下:

level:1,ouput:php1
level:2,ouput:php2
level:3,ouput:php3

当然,当你关闭某个级别的缓冲,如下测试:

ob_end_clean();
 
ob_start();
echo &#39;php1&#39;;
$a = ob_get_level();
$b = ob_get_contents();
ob_clean();
 
ob_start();
echo &#39;php2&#39;;
$c = ob_get_level();
$d = ob_get_contents();
ob_end_clean();  //清空缓存并关闭缓存
 
ob_start();
echo &#39;php3&#39;;
$e = ob_get_level();
$f = ob_get_contents();
ob_clean();
 
echo &#39;level:&#39;.$a.&#39;,ouput:&#39;.$b.&#39;<br>&#39;;
echo &#39;level:&#39;.$c.&#39;,ouput:&#39;.$d.&#39;<br>&#39;;
echo &#39;level:&#39;.$e.&#39;,ouput:&#39;.$f.&#39;<br>&#39;;

结果如下:

level:1,ouput:php1
level:2,ouput:php2
level:2,ouput:php3

相关推荐:

PHP 缓存机制

php 缓存工具类 实现网页缓存

thinkPHP 缓存机制

以上是PHP嵌套输出缓存实例的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn