|

PHP Code Structure

PHP Code Structure

PHP is a fun language to work in for both beginners and professionals alike. In this PHP Tutorial Series, we’re starting at the ground floor of working with PHP. It’s really awesome to start from the beginning even for more experienced developers that need a refresh. Many times, you’ll find advanced problems often come back around to being very basic missteps. This is what makes the basics so very important. They are the foundation that you will build your entire programming knowledge base on. So now that we have taken a look at what PHP is and the history of this sometimes controversial language, let’s start getting our hands dirty with PHP. In this episode we’ll take a look at some of the very basics of the language as well as the request lifecycle and where PHP fits in to that. Much of these snippets of information are simply bread and butter basics that we need to know before we go all ninja on ourselves. Let’s get started!


Placing PHP in your Web Page

The primary way to use PHP is to embed it within an HTML page. There are two things to know about placing PHP inside of your HTML files. We know that when a user makes a request of a website, it is using HTTP to fetch an HTML file. The web server in turn sends the file to the end user and their web browser interprets that HTML and renders a web page for viewing. This is entirely static. To begin to make things dynamic, let’s add some PHP.

index.php

<?php and ?>

The <?php and ?> are the opening and closing tags of PHP. This is what tells the web server to stop reading the contents of the file as static HTML, and to begin reading the contents as PHP. Recall this goes in a top down sequence and when there is no longer any PHP to interpret by the web server, we add a closing tag to indicate that we are back to HTML.

Files Must have a .PHP Extension

Any files that live on your web server must have the .php extension in order to use PHP within the page. Files of this type can have native HTML and PHP code mixed together as long as you are making use of the opening and closing PHP tags.

Alternate Tag Styles

There are alternate tag styles available to you to denote the opening and closing locations of PHP within your files. Be advised however, that if you use them, you may find yourself the target of the PHP police as most of these are bad form. Here are two of the other styles you can use.

Short Open Tags  – <? and ?> as well as <?= and ?> – This is a bad idea.

ASP Style Tags  – <% and %> as well as <%= and %> – This is a very bad idea.

So why are these a bad idea? Well, remember that one of the goals of writing software is that you want your code to be able to run in as many environments as possible with the least amount of additional configuration required. Now, I know you’re lazy you want to speed up your workflow and save a few keystrokes but here is the deal, you should use <?php and ?> as your starting and ending tags for PHP because this gives you the most amount of portability. The next two will work but you may need to edit the php.ini file in order to do so. What if you write a plugin for WordPress and someone out in the wild can not get it to run because you decided to use ASP Style Tags exclusively and their hosting company does not allow ASP Style Tags? That’s not a situation you want to have.


PHP For Dynamic Websites

By using PHP, we can begin to make our websites dynamic. In fact you are viewing a dynamic website on this very webpage. This is because most of the content you are consuming right now is stored in a database, not in a static HTML file. By using PHP, we can interact with a database and get dynamically generated content to serve based on many criteria. Let’s walk before running though and start with some simple commands.

echo

Just above, we had already made use of the echo command in PHP. Using this command, we can do exactly what it says, echo something to the screen. There is another way to do this as well. In fact, almost anything you can do in programming, you’ll find that there are many ways to do the same thing. For example, we could rewrite our prior example using the print command just like this.

index.php

Whether we use the first example of echo or the second of print, they will both produce exactly the same thing in the browser. In fact in both scenarios, if you choose View Source in your web browser, you can take a look at the HTML that was dynamically generated and in both cases it looks just like this.

So that is great, and you may be wondering, “Well should I use echo or print?” What is the difference between echo and print in PHP? There are a couple of differences to be aware of.

  1. echo is faster When PHP executes, the echo command will run faster than the print statement. To be fair, you wouldn’t in a million years be able to tell the difference because it is so minute, yet it is a fact that echo is faster.
  2. print is a true function In PHP, the echo statement is not a language construct however the print function is. This makes assigning a return value possible with the print statement. This is a beginner tutorial however so we’ll just stick to using echo unless we come across a need for print.

Studying The Request Response Cycle

A key ingredient to understanding how dynamic web pages work is to study the Request Response Cycle. This encompasses the entire life cycle of requesting a webpage in your browser from a remote server all the way to rendering it on the screen. How does this process happen? Let’s imagine we are using the Google Chrome web browser and we are requesting to view the index.php file on a remote linux server that is using the apache web server software, PHP, and a MySQL Database. The process looks like this.

Chrome makes an HTTP request The first step is for the web browser to send an HTTP request to the web server in question. This is simply a matter of loading something like http://example.com/index.php in your browser.

  • Apache finds the file This request is interpreted by Apache, and it looks in the filesystem to find the index.php file.
  • The file is interpreted by the PHP engine The web server knows that this file must be run through the PHP Engine since it has a .php extension.
  • The MySQL Database is queried If the file contains any logic to perform a database interaction, it happens at this step.
  • Output is sent to the Browser The data is returned from the database, all PHP is parsed, and all data is then wrapped up into the final HTML output which gets sent back to the client. Chrome renders this HTML in the browser and displays a web page to the user.

The PHP Interpreter Does Not Care About Whitespace

Much like JavaScript, the PHP Engine does not care about whitespace. With JavaScript, we always see developers minify their code before production. This strips out all whitespace and non essential characters to produce one massive string of largely unreadable JavaScript. The web browser doesn’t care however, it is able to run the JavaScript just the same. With PHP, it is the same idea. There is no need for minification on the server side however since the file size is not important. The PHP code itself will live on the server and stay on the server as it executes, unlike JavaScript which must be sent across the network before the Web Browser can do it’s thing.

This example function will run just fine when called upon.

However, you will make things infinitely easier on yourself if you use common formatting to make the code readable.

If the above snippet doesn’t make a ton of sense to you, no need to worry. We’re only using this to display the value of whitespace to the human coder, that would be you, and the fact that the machine doesn’t care how the code is formatted – it simply reads in source following the delimiters and control structures of the language as its means to process it.

PHP Comments Syntax

We’ll now talk a little bit about comments in PHP and the syntax to use them. Comments are so important, some would say even more important than the code itself. No matter what language you happen to be programming in, using proper comments will save yourself and other programmers that happen to be working on the project untold hours of frustration while debugging. The funny thing is, is that when you are originally writing the code and it comes time to include some comments, it is so easy to think, “This is so obvious what is being done here, why would I ever need to add any comments?” If you have ever found yourself thinking this, and then came back to this very same code six months or a year later to hack in a modification, you’ll know how much it hurts to look at that code and wonder what in this good green earths name were you thinking?! Now consider that fact that you yourself are having a hard time figuring out what you did in this earlier revision of the code. Now think about some other unlucky developer that has had to take over your duties and codebase. If you’re having a hard time figuring things out here, think of how this other dev must feel! These examples we’ll show here really don’t need comments, but we’ll use these simple examples to just show how to use the syntax of comments in your own php files.

In the snippet above we make use of all three styles of comments you can use. You can try all of them out and see which feels most natural. You can get really creative with these and outline very specific comments at the beginning of various functions, classes, methods, and so on. You’ll find that the popular PHP Frameworks have fantastic comments.

  • C++ Style Comments These are one line style comments using the double forward slash notation //
  • Multi Line Comments By using an opening /* and closing */ you can spread the comment across several lines.
  • Shell Style Comments Finally, you have the option of using shell style comments with the hashtag # character.

The PHP Code Structure Summary

In this PHP Tutorial Series, we took a look at some key ingredients in getting yourself up to speed with the overall structure of the PHP language. Can you do anything cool in PHP yet? Well, probably not with just the info from this article. The key is however, though you may want to jump into the most advanced php frameworks and do awesome things – if you don’t know that basic structure of the code it uses, you won’t have a clue about what to do when things don’t go right. There will be times when things don’t go right! So with that in mind, we covered some real basic stuff here such as embedding php in a web page, using proper start and end tags for your php code, making use of the right extension on php files, using php for dynamic websites, learning about the request response lifecycle, whitespace considerations, php code comments, and more. Now we’re ready to get busy and start learning about how to make cool things happen in php in the coming posts.