While the HiJacob program was interesting, there was no real advantage to using a variable. Now you will see another use of variables that shows how useful they can be.
Figure 2.5 shows the "Row Your Boat" page.
I chose this song in particular because it repeats the same verse three times. If you look at the original code for the rowBoat.php program, you'll see I used a special trick to save some typing.
<html> <head> <title>Row Your Boat</title> </head> <body> <h1>Row Your Boat</h1> <h3>Demonstrates use of long variables</h3> <? $verse = <<<HERE Row, Row, Row, your boat<br> Gently down the stream<br> Merrily, merrily, merrily, merrily<br> Life is but a dream!<br> <br><br> HERE; print "<h3>Verse 1:</h3>"; print $verse; print "<h3>Verse 2:</h3>"; print $verse; print "<h3>Verse 3:</h3>"; print $verse; ?> </body> </html>
You'll frequently find yourself wanting to print several lines of HTML code at once. It can be very tedious to use quote signs to indicate such strings (especially because HTML also often uses the quote symbol). PHP provides a special quoting mechanism, which is perfect for this type of situation. The line
$verse = <<<HERE
begins assigning a value to the $verse variable. The <<<HERE segment indicates this will be a special multi-line string that will end with the symbol "HERE." You can use any phrase you wish, but I generally use the word HERE because I think of the three less than symbols as "up to." In other words, you can think of
$verse = <<<HERE
as meaning "verse gets everything up to HERE."
You can also think of <<<HERE as a special quote sign, which is ended with the value HERE.
You can write as much text as you wish between <<<HERE and HERE. You can put variables inside the special text, and PHP will replace the variable with its value, just like in ordinary (quoted) strings. The ending phrase (HERE) must be on a line by itself, and there must be no leading spaces in front of it.
TRAP? |
You might wonder why the $verse = <<<HERE line doesn't have a semicolon after it. Although this is one line in the editor, it begins a multi-line structure. Technically, everything from that line to the end of the HERE; line is part of the same logical line, even though the code takes up several lines in the editor. Everything between <<<HERE and HERE is a string value. The semicolon doesn't have any special meaning inside a string. If this doesn't make sense to you, don't worry about it for now, as you'll get some other chances to think about this concept later. As a minimum, you should know that a line beginning a multi-line quote doesn't need a semicolon, but the line at the end of the quote does. |
Once the multi-line string is built, it is very easy to use. It's actually harder to write the captions for the three verses than the verses themselves. The print statement simply places the value of the $verse variable in the appropriate spots of the output HTML.