PHP nested output Buffer Code instance _php

Source: Internet
Author: User
The output cache of PHP can be nested. The nesting level can be output with ob_get_level ().
The test found a different output in the CLI and the browser (PHP5.4).

The manual is described below:

Ob_get_level () would always return 0 inside a destructor.
This happens because the garbage collection for output buffers have already done before the destructor is called

It's also easy to get the right output:

The code is as follows:


Ob_end_clean ();
Echo Ob_get_level (); 0

Back to the chase:

The code is as follows:


Ob_end_clean ();

Ob_start ();
Echo ' PHP1 ';//This is not output in the page
$a = Ob_get_level ();
$b = Ob_get_contents ();//Get cached results, assign variables
Ob_clean ();

Ob_start ();
Echo ' PHP2 ';//This is not output in the page
$c = Ob_get_level ();
$d = Ob_get_contents ();//Get cached results, assign variables
Ob_clean ();

Ob_start ();
Echo ' php3 ';//This is not output in the page
$e = Ob_get_level ();
$f = Ob_get_contents ();//Get cached results, assign variables
Ob_clean ();

echo ' Level: '. $a. ', ouput: '. $b. '
';
echo ' Level: '. $c. ', ouput: '. $d. '
';
echo ' Level: '. $e. ', ouput: '. $f. '
';

The results are as follows:

The code is as follows:


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

Of course, when you turn off a level of buffering, the following tests:

The code is 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 (); Empty the cache and close the cache

Ob_start ();
Echo ' php3 ';
$e = Ob_get_level ();
$f = Ob_get_contents ();
Ob_clean ();

echo ' Level: '. $a. ', ouput: '. $b. '
';
echo ' Level: '. $c. ', ouput: '. $d. '
';
echo ' Level: '. $e. ', ouput: '. $f. '
';

The results are as follows:

The code is as follows:


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

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.