PHP variable scope between code blocks

You’re putting too much meaning in the php code blocks.
It’s not something that global.
These blocks belong to the same PHP script. It’s just a neat way to output HTML, nothing more. You can substitute it with echoing the HTML and there will not be the slightest difference.

The whole PHP script is being executed at once, not in iterations, as you probably picture this, thinking that PHP blocks are being executed server-side, then HTML blocks client-side, and then back to PHP blocks on the server side and so on. That’s wrong.
The whole PHP script is being executed on the server side, resulting with pure HTML in the browser, and then dies.

That’s why you can’t program both an HTML form and its handler in the same PHP script by just placing the latter one right after the former. You have to make another call to the server to make the handler work. It will be another call completely, another instance of the same script, knowing nothing of the previous call which is long dead already. And that’s another thing you have to know about PHP:

PHP script execution is atomic. It’s not like a desktop application constantly running in your browser, or even a daemon with persistent connection to your desktop application. It’s more like a command-line utility – doing its job and exits. It runs discretely:

  1. a browser makes a call
  2. PHP wakes up, creates an HTML page, sends it to the browser and dies
  3. Browser renders that HTML and shows it to the user.
  4. User clicks a link
  5. a browser makes a call
  6. another PHP instance, knowing nothing of the previous call, wakes up and so on

Leave a Comment