Lesson 2 – PHP Syntax

PHP has a very simple syntax. As it is embedded in HTML, you need a way to differentiate it from HTML and other elements on the document, the process commonly known as “Escaping to PHP.”

One of the most effective and popular methods to escape to PHP is to use canonical PHP tags that look as follows.

<?php ?>

This is actually the standard method of escaping to PHP. Therefore, the browser will always correctly interpret every PHP code inside these tags.

The other method is to put Short-open (SGML-style) tags where you want to include PHP in your document. These tags look something like this.

<? ?>

As you may expect, shot tags are the easiest and shortest option However, PHP requires you to do two things before it can recognize these tags.

  • Always go for the –enable-short-tags configuration option when you are working in PHP.
  • Turn on the short_open_tag setting in your php.ini file.

You can also use ASP Style Tags which look as follows to differentiate PHP from HTML. These tags look very similar to the one used by Active Server Pages to execute pieces of code.

<% %>

Once again, you will have to configure your php.ini file to properly use ASP Style tags.

The last option is to employ HTML Script tags to develop in PHP. Here is how it is done.

<script language=”PHP”><script>  

Commenting in PHP

Just like every other programing language, PHP also allows you to add comments to your code. The comments are for human use only. Browsers do not consider comments as a part of the code and therefore, ignore them while displaying the program results. Developers put code in their codes for short explanations and briefs for other developers.

Adding comments in PHP is not that difficult either. All you have to do is to put a pair of forward slashes (//) followed by the actual comment. Here is an example.

// This is a comment. 
print "This is an example of a single line comment.";

As you can see in the below image, the browser has parsed only the piece of code that is in the double quotes. It has totally stripped out the comment.

Now if you want to add a multi-line comment, you will put a forward slash followed by an asterisk sign before the comment. Similarly, you will end the comment by putting an asterisk followed by a forward slash after the comment.  

/* This is a multi-line comment. 
   It spans over multiple lines.*/ 
print "This is an example of multi-line comment"

The outcome of the above code is as below.

In the next lesson, we will study PHP variables and their types.