GuidesWelcome to the World of PHP Page 4

Welcome to the World of PHP Page 4

ServerWatch content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

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 
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"); ?> 

Today's Headline:

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 tags.


Get the Free Newsletter!

Subscribe to Daily Tech Insider for top news, trends & analysis

Latest Posts

Related Stories