1. Background
There is a piece of code that because the encapsulated method is called, there will be some return values that are not needed. How to deal with these return values to make it disappear. Some people will say, isn’t it good to just clear variables? But what if this return value cannot be cleared?
2. ob_start()
1. Concept:
This function will turn on the output buffer. When the output buffer is activated, the script will not output the content (except the http header), instead the content that needs to be output is stored in the internal buffer.
The contents of the internal buffer can be copied into a string variable using the ob_get_contents() function. To output content stored in the internal buffer, you can use the ob_end_flush() function. In addition, using the ob_end_clean() function will silently discard the contents of the buffer.
From the php manual:/manual/zh/
2. Basic usage of buffers
//Open the bufferob_start(); //Clear content in the bufferob_clean(); //Flush out (send) the output buffer content and turn off the bufferob_end_flush();
3. Basic tests
1、
echo '1'; ob_start(); echo '2'; ob_clean();
Results: 1
Explanation: This is the easiest way to use it, which is to add ob_start(); to the outside of the content that you don't want to output, and then clear the content in the buffer, which realizes our usage scenario. We can selectively output what we want to output. Remove what you don't want to output.
2、
echo '1'; ob_start(); echo '2'; //Output bufferob_end_flush();
Results: 12
3、
//Open the bufferob_start(); echo '1'; //Clear the buffer, no 1 will be output at this timeob_clean(); //Output buffer. However, because the buffer has been cleared above, 1 will not be outputob_end_flush(); echo '2';
Results: 2
4、
ob_start(); //Open the bufferecho '1'; $a = ob_get_contents(); //The output buffer contents are $a, which is equivalent to assigning value to $aob_clean(); //Clear the buffer content hereecho '2'; //Output 2echo $a; //Output$a
Results: 2 1
Explanation: The ob_get_contents(); here is the content of the buffer. We can assign the obtained content to a variable, so that even if the buffer is cleared, we can still output 1 normally.
4. Commonly used places
This function is often used to static pages, and constructing a micro web framework can play a very critical role. The rendered page is written directly to a file through input cache. In this way, it can determine whether the file exists. It can be realized whether the user needs to re-render a page during this access. It can also be applied to large projects. Use nosql to store the rendered page. The specific usage method varies from person to person, and it depends on which type you like
The above is a simple test I did myself. If you need it, you can compare it with the php manual and do more tests.