Home >Backend Development >PHP Tutorial >PHP nested output cache example

PHP nested output cache example

*文
*文Original
2017-12-26 15:18:001149browse

How does PHP implement nested output caching? This article mainly introduces PHP nested output caching code examples, and uses the ob series functions to solve nested output caching examples. I hope to be helpful.

PHP’s output cache can be nested. Use ob_get_level() to output the nesting level.
The test found that the output results are different under the cli and the browser (PHP5.4).

The manual instructions are as follows:

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

It is also very simple to output correctly:

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

Back to the topic:

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;;

The results are as follows:

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

Of course, when you turn off a certain level of buffering, test as follows:

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;;

The results are as follows:

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

Related recommendations:

PHP caching mechanism

php caching tool class to implement web page caching

thinkPHP caching mechanism

The above is the detailed content of PHP nested output cache example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn