I am kind of confused about how the below code works. In my head I am imagining each php block being executed as a whole and rendered to HTML. The fact that the first block is kind of incomplete with a hanging brace doesn't play nicely with how I imagine PHP to work. What does the PHP module do when it gets to a PHP closing tag? How is it that code inside the PHP tags can effect the output of plaintext outside of the PHP tags, i.e. only conditionally outputting the form?
I would have thought that to accomplish the below you would have actually had to use an echo statement to conditionally echo the form.
<html>
<head></head>
<body>
<?php
/* if the "submit" variable does not exist, the form has not been submitted - display initial page */
if (!isset($_POST['submit'])) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Enter your age: <input name="age" size="2">
<input type="submit" name="submit" value="Go">
</form>
<?php
}
else {
/* if the "submit" variable exists, the form has been submitted - look for and process form data */
// display result
$age = $_POST['age'];
if ($age >= 21) {
echo 'Come on in, we have alcohol and music awaiting you!';
}
else {
echo 'You're too young for this club, come back when you're a little older';
}
}
?>
</body>
</html>
The closing tag of a PHP block at the end of a file is optional, and in some cases omitting it is helpful when using include or require, so unwanted whitespace will not occur at the end of files, and you will still be able to add headers to the response later.
In PHP, statements are terminated by a semicolon (;) like C or Perl. The closing tag of a block of PHP code automatically implies a semicolon, there is no need to have a semicolon terminating the last line of a PHP block.
The only invalid tags are <! !>.
An opening tag begins a section of page content, and a closing tag ends it. For example, to markup a section of text as a paragraph, you would open the paragraph with an opening paragraph tag <p> and close it with a closing paragraph tag </p> (closing tags always proceed the element with a /).
The PHP manual explains it pretty decently:
...when PHP hits the
?>
closing tags, it simply starts outputting whatever it finds (except for an immediately following newline - see instruction separation ) until it hits another opening tag ... but for outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text throughecho()
orprint()
...
The parts outside of the php tags are treated as literals that are outputted in that part of the program flow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With