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 'level:'.$a.',ouput:'.$b.'<br>'; echo 'level:'.$c.',ouput:'.$d.'<br>'; echo 'level:'.$e.',ouput:'.$f.'<br>';
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 'php1'; $a = ob_get_level(); $b = ob_get_contents(); ob_clean(); ob_start(); echo 'php2'; $c = ob_get_level(); $d = ob_get_contents(); ob_end_clean(); //清空缓存并关闭缓存 ob_start(); echo 'php3'; $e = ob_get_level(); $f = ob_get_contents(); ob_clean(); echo 'level:'.$a.',ouput:'.$b.'<br>'; echo 'level:'.$c.',ouput:'.$d.'<br>'; echo 'level:'.$e.',ouput:'.$f.'<br>';
The results are as follows:
level:1,ouput:php1 level:2,ouput:php2 level:2,ouput:php3
Related recommendations:
php caching tool class to implement web page caching
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!