Welcome to the World of PHP Page 4

PHP Structure

We have not yet discussed the PHP language itself, so let's focus on structure for now. The above page contains a small section of PHP code, which assigns a value to a variable $today. A second block of PHP code in the middle of the page outputs our headline, and a third block of PHP near the end of the page uses the $today variable to output the day of the week. Given that today (the day I'm writing this, not necessarily the day you're reading it!) is Wednesday, the above code would produce the page:

Today's Headline:

World Peace Declared

Today is Wednesday

Besides breaking up PHP code into multiple blocks, it is possible to include code from external files into pages. Sometimes you may wish to keep bits of code in its own file -- for example, HTML code that makes up a repeating element such as a logo or footer, or PHP code that makes up a function that will be used in several different pages. Returning to the previous example, suppose we break out the footer into its own file, and the initial PHP block into its own file:

setdate.php3: <?php 
footer.php3: <!-- begin footer -->
<SMALL>Today is <?php
print $today[weekday];

Now, we can use PHP's include() function to pull the above files into our example page:

<?php include ("setdate.php3"); ?> <H2>Today's Headline:</H2> <P ALIGN="center"> <?php print "World Peace Declared"; ?> </P><HR> <?php
include ("footer.php3");

The most common use for the include() function is, as seen above, to reuse certain components across several pages. Of course, your components will often contain much more code that the examples shown here! Also notice that each component is treated as an HTML page -- that is, it can contain HTML tags and any PHP code must appear within the <?php ... ?> tags.


This article was originally published on Jul 7, 2000

Thanks for your registration, follow us on our social networks to keep up-to-date