Question:
Please explain finally WHAT exactly these functions do (explain simply, I'm a beginner) and what is the difference between them. I don’t understand, for the life of me, on the forums everyone uses terminology that only confuses those who encountered them for the first time. And what are the top and bottom layers of the buffer stack? What is a buffer stack? What are the layers? If someone can explain this in an accessible way, it will help me a lot. Thank you very much in advance
Answer:
If you explain in simple terms, when echo / print is called, then the data goes to the output (for example, the browser). In order not to drive byte by byte with numerous echoes, there is an output buffer where the output data is accumulated up to a certain volume and, when overflowed, the data is sent to the output. Then the data is collected again. flush forces the contents of the buffer to be flushed to the output stream.
For example, you have a long task where you need to constantly send results to the browser and you use echo "information". But they accumulate in the buffer and the browser will not receive anything until the buffer overflows. flush after echo forces the data to be sent. Also, the buffer can be disabled, but in cli mode it is not there at all.
ob_* allows you to initialize your nested buffers by layering them on top of each other. And when clearing the data of such a buffer, it will fall into the underlying one up to the default one. Or you can not flush at all, but simply take the accumulated result from the buffer and destroy it.
ob_start opens a new buffer and all subsequent print/echo will fall into it. At any time, you can open a new buffer, or you can close and reset the current one to the previously opened buffer. That is, it looks like a layered pie (stack) of buffers, where data is written to the upper buffer and only when all buffers are flushed to the underlying ones up to the default one, only then the data will not be output.
It is convenient to use it in a self-written template engine. For the template segment, we create a buffer and then we take the finished html and destroy the buffer. Or when we call third-party code that is replete with echo and creates garbage, we wrap its call in ob_* and all this garbage settles there.
i.e. flush flushes the system buffer to output, and ob_flush flushes the last opened buffer via ob_start to the underlying buffer (ob_* or system)