PHP Syntax - PHP QuickStart Guide (2015)

PHP QuickStart Guide (2015)

Chapter 4: PHP Syntax

In programming, “syntax” is the term used to describe the rules for how characters are used. Each text-based programming language, like PHP, uses a specific set of characters designated for particular purposes. The syntax of the language determines how those “reserved” characters are used to construct the elements of a program. The most basic of those elements – the building blocks of the programming language - are known as “constructs.” In this chapter, we'll examine how those constructs form the basic syntax of PHP.

Beginning and Ending Tags

PHP code is written between beginning and ending constructs called “tags” made up of a specific series of characters. This section will explain how these tags are used.

In a standard PHP environment, the most commonly used format is:

<?php somePHPcommand; ?>

Or

<?php

somePHPcommand;
somePHPcommand;
somePHPcommand;

?>

In each of the examples above, “<?php” is the beginning tag and “?>” is the ending tag. These are the standard tags that enclose a block of PHP code. These 2 tags tell the interpreter on the web server when to start and stop processing the text as PHP code.

Note: Remember that PHP is a pre-processor – the lines of code are processed before being sent to the web browser.

Some web servers may be configured to allow different starting and ending tags. For instance, many will allow the short version of the opening tag:<? tobe used. Still others may allow Active Server Page (ASP)-style tags:<% %>.In many environments, the standard script tags for HTML can be used:<script language="php"> </script>. For our purposes, and as a suggested best practice, this book will use the standard tags, as shown in our two examples above.

Note: When a file contains only PHP code, the ending tag may be omitted. This is often recommended to avoid the output of a newline character. If the PHP code is followed by anything, including comments, HTML or text, the ending tag must be present. The examples in this book will always use the closing tag.

PHP Statements

In PHP, statements must be terminated with a semicolon (;). This makes the semicolon a delimiter in the PHP language, which is a character that separates types of text.

Note: There is, however, one exception to the semicolon rule, in which the last statement in a function or block of PHP code doesn't require a semicolon.

The PHP interpreter ignores line returns, blank lines and spaces between statements. The following code block structures are all valid and will produce identical results:

<?php statement1;statement2;statement3; ?>

<?php statement1; statement2; statement3; ?>

<?php
statement1; //(cont'd on next page)
statement2;
statement3;
?>

<?php
statement1;
statement2;
statement3;
?>

This provides great versatility in creating your PHP applications and allows developers to arrange code in ways that make for very easy troubleshooting and general review.

Note: Standards have been developed for consistency in spacing, indenting, and placement of characters in PHP coding. A resource for those standards can be found in Appendix A.

Variable Declarations

As discussed in the previous chapter, PHP variables are created with a declaration statement. We'll be using variables in many of the upcoming code examples, so let's look at how to declare a variable. In PHP, a declaration statement simply contains the variable name (preceded by the “$” sign), followed by an equality sign (= ) and the initial value that the variable will represent. (Remember, spaces are ignored in your code, so they can be included for better readability.)

The following are all valid declaration statements:

<?php

$product = 'Little Red Wagon';

$price = 2.95;

$sales_tax = $price * 0.08;

$total = "$".$price + $total;

?>

In the preceding code block, note that the value for the first variable,$product, is enclosed in single quotation marks. This tells PHP that the text is to be treated as string, which is explained in the following section. What's important to understand in this example is that the spaces in the string will not be ignored and are stored as characters in the string.

The second variable contains a numeric value, which we don't enclose in quotes to avoid it being stored as a string. In the third, we perform a mathematical operation; (*) is the multiplication operator on a predefined variable to arrive at the value. In the last, we add the values of 2 variables, using only the variable names in the operation. This illustrates the versatility of variables in PHP.

Comments

Most text-based programming languages allow the use of comments, which are lines of text entered strictly for providing information about the code. These lines of text are separated by special delimiters and are ignored by the interpreter when the program runs. Comments are important tools for programmers. They allow:

1) Labels to separate sections of a program

2) Explanations of program elements

3) Documentation for other programmers,

4) Instructions for users of the program,

5) Notes for themselves, and

6) Disabling lines of code temporarily for troubleshooting.

Experienced programmers use comments extensively to simplify the job. They'll be used in our code examples in this book, too, so it's important to recognize them. Delimiters are used to separate these comments from executable code. There are three types of comment delimiters in PHP. The code examples below demonstrate how they're used.

Single-line comments can be marked with either the hash character(#)or a pair of slashes(//):

<?php //This line won't output anything ?>

<?php #This line won't, either ?>

Multi-line comments can also be added. They require an opening delimiter (/*) and a closing delimiter (*/), as below:

<?php

/* None of these lines will print.
This is a comment!
So is this.*/

?>

Comments can be placed anywhere within code blocks:

<?php
echo 'this is a comment'; //this will output the text shown.

# echo 'this is a comment'; //this line will output nothing.

/*

The method above is very handy for disabling one line of code at a time for troubleshooting purposes. As demonstrated in this multi-line comment, you can create as many lines of comments as you like using this method, until you type the ending delimiter, below:

*/

echo 'This text will be displayed';

/****** Let's put a comment here ******/
?>

Quotes and Strings

In programming, a string is a block of text that should be treated as text when the program is executed. In most cases, a string will be output to the display or other device as readable text. Programming languages, such as PHP,use quotation marks(' or ")to differentiate strings from other text. The type of quotation marks used to enclose a block of text is important.

Note:Quotation marks, like those in this text, commonly known as “magic quotes” or “curly quotes” are not used for programming code. Those characters are generated by special character codes. When programming, be certain to set your text editor to use straight quotes(')and (")

In PHP, all strings are parsed, meaning that the Zend Engine looks for variables, operators, formulas, etc. within the strings. Quotes give programmers some control over how strings are parsed.

Single Quotes: If a string is enclosed in single quotes ('), it will be considered literal, meaning that operators, etc. won't be evaluated. In other words, the strings will print as they are. There are some exceptions, most notably the single-quote character itself, since it will be interpreted as the end of the string, and the backslash (\) character, since it's the escape character for PHP. To print those characters correctly, they must be preceded by a backslash. For example:

<?php
echo 'Don\'t forget to use a \\ before a backslash.';
?>

Double Quotes: Strings enclosed in double quotes (") will have their operators, variables, etc. evaluated when parsed, so values will be substituted. For instance, this code:

<?php $chr = 34; echo "This string contains $chr characters." ?>

Will print “This string contains 34 characters.” If a variable needs to be paired directly with text in this syntax, enclosing it in curly braces will designate where the variable begins and ends:

<?php $chr = 'alpha'; echo "This string contains {$chr}numeric characters." ?>

The code block above will print, “This string contains alphanumeric characters.”

heredoc and nowdoc: PHP includes two special types of string syntax that use a special operator (<<<). By using this operator and an identifier, complex, multi-line strings can be printed without the need for complex escaping.

The “heredoc” syntax lets you print strings with evaluation. To use this syntax, simply use the operator followed by an identifier that you define, followed by a newline and the string to be parsed. To end the string, type the identifier and a semicolon on a blank line below it.

Note: this line may not contain any other characters, including any spaces or tabs to indent it.

Here's an example of heredoc syntax:

<?php
$a = 'all';
$b = 3;
echo <<<EOS
This string will be printed with $a of its variables evaluated.
Escape characters like the newline above will also be evaluated, so basic
text formatting will be included. (this is line $b)
EOS;
?>

The code above will output:


This string will be printed with all of its variables evaluated.
Escape characters like the newline above will also be evaluated, so basic
text formatting will be included. (this is line 3)”

The “nowdoc” syntax operates identically to heredoc, without evaluation of variables. Unlike strings enclosed in single quotes, strings printed in this syntax do not require escaping of single quotes and backslashes.

Using nowdoc syntax is identical to heredoc, except that the identifier is enclosed in single quotes. Here's an example:

<?php
$a = 'all';
$b = 3;
echo <<<'EOS'
This string won't require using the \ character.
It will print $a variables exactly as they're typed.
EOS;
?>

The code above will output the following:

“This string won't require using the \ character.
It will print $a variables exactly as they're typed.”

These are the basic syntax guidelines for PHP. Syntax for individual elements such as functions, classes, etc. will be covered within the chapters for those elements.

Control Structures

Control structures vary somewhat according to their type and the keywords used to create them. However, there are two basic types of syntax used for creating them. The “standard” syntax is as follows:

keyword (parameters) { group of statements }

The example above represents only the syntactic elements used to group the portions of the structure. Because PHP allows us to use line breaks, spaces, etc. to organize our code, it's usually more convenient to build the structures like this:

keyword (parameters) {

statement1;
statement2;
statement3;

}

Again, this is only a basic example of the syntax used to build control structures. Structures may be nested within structures and there will often be multiple options. For instance, a basic “if/else” structure might look like this:

if ($roses == 'red'){
if ($violets == 'blue'){
echo 'Sugar is sweet';

} else {

echo 'Violets are purple';

}

If the code above doesn't make sense to you yet, don't worry; we'll go over these structures many times in the upcoming pages. For now, just focus on the way the parameters of the control and the instructional statements are grouped.

As previously mentioned, this is one of two choices of syntax for most control structures. The “alternate” syntax is shown in the example below, using the same control structure as above:

if ($roses == 'red') :

if ($violets == 'blue') :

echo 'Sugar is sweet';

endif;

else :

echo 'Violets are purple';

endif;

Note that the curly braces ({}) have been replaced with a colon (:) and another keyword, “endif.” Otherwise, the structure remains the same. This syntax lends itself well to some applications. It's also the basis for a “shortcut” syntax, and we'll cover both of those topics in the next chapter.