Crash Course in PHP


PHP is a server-side scripting language especially suited for developing websites. It has many functions designed to interface with XHTML, and PHP code can be embedded directly into XHTML to create dynamic sites. With most PHP development, PHP logic is applied to dynamic content, combining function and layout, to produce standard XHTML code, which is then served to a client browser. PostNuke works entirely in this fashion.

The following sections review the basics of the PHP language, its syntax, and recommended coding standards.

PHP Syntax

PHP is a C-style language, so its syntax is very similar to other languages of the type, such as C++, Java, and JavaScript. If you are already familiar with one or more other C-style languages, learning PHP should come very easily.

All PHP Is Contained Within Markers That Bracket the Code

The server needs the markers to know when to interpret the content as PHP and when to leave it as simple XHTML. Within a given page, you can open and close PHP code areas as many times as you need. Outside of the PHP, XHTML is handled normally, and if you need to write out XHTML from inside a block of PHP, you can use PHP commands to write out the content.

PHP code blocks begin with this:

 <?php 

and end with this:

 ?> 

There are alternative opening/closing markers, but they are intended for shorthand and language translation uses. All standard PHP should be bracketed with the preceding syntax, and every PHP code block you encounter in PostNuke will use the preceding syntax.

Every PHP Statement Must End with a Semicolon

This is a common practice with many other languages as well. The only two exceptions to this rule in PHP are when a statement ends in a curly bracket, when the bracket has already ended the statement and a semicolon will create an unneeded new empty statement, or if the statement is the last line before the close of a PHP code block, when the semicolon is optional.

Here is an example bit of code that illustrates the semicolon use:

 <?php $test = TRUE;                 // semicolon required echo 'hello world!';          // semicolon required if ($test) {     echo 'Test is true.';     // semicolon required }                             // semicolon forbidden else {     echo 'Test is false.';    // semicolon required }                             // semicolon forbidden echo 'The test is complete.'; // semicolon optional ?> 

It's a good idea to always add the semicolon even under optional circumstances. It saves the trouble of checking for missing semicolons when you add additional code between the last statement and the end of the code block.

PHP Ignores Whitespace and Line Breaks

Because statement endings are marked with semicolons, the line break formatting of PHP code is more for the benefit of programmers working with the language. It's possible to shorten statements and even run lines together if desired. A common practice that shortens the previous example is to remove blank lines and tighten up extended statements:

 <?php echo 'hello world!';; if ($test) {     echo 'Test is true.'; } else {     echo 'Test is false.'; } echo 'The test is complete.'; ?> 

The code can also be written even tighter this way:

 <?php echo 'hello world!'; if ($test) { echo 'Test is true.'; }     else { echo 'Test is false.'; } echo 'The test is complete.'; ?> 

Much of the formatting of PHP will come from your own style preferences. The most important thing to do is stay consistent with whatever your style is.

Line Indents Are Four Spaces

Each line should be indented with four spaces. Do not use a tab; some editors might view the tab consistent with spacing, but many do not. You might find when you change editors that your tabbed PHP is suddenly very hard to read.

Four spaces specifically have been set as the standard for an indent. Though you might see some code occasionally using indents of three spaces, all new writing should use four spaces to be consistent.

PHP Is Case Sensitive, Sort Of

PHP is only case sensitive when it comes to user-defined variables, but again consistency demands that you write all PHP as though it were fully case sensitive. The style standards promote the use of lowercase characters for all regular code. This standard is also consistent with XHTML requirements.

Variables, Data Types, and Operators

PHP variables contain content values of various data types, which are referenced, compared, and modified using operators. The way PHP variables are handled is very straightforward, and anyone familiar with programming in any language will immediately recognize the PHP data types and operators. Specific information to note about how PHP handles them is discussed in the following sections.

Variable Identifiers Must Begin with a Letter or Underscore

This is true for many languages, and also applies to function and object identifiers. The underscore character (_) used with a variable denotes a global variable. After the first character, the numbers 09 are also valid.

Tip

Extended ASCII characters in the range of 0x7F to 0xFF are also valid starting characters. They are designed to support European language character sets.


Variable Names Are Always Preceded by $

You can always tell a PHP variable by the $ (dollar sign) in front of it. The dollar sign provides confirmation that a given identifier is a variable and not a function or object definition. For example:

 $myNumberVariable = 5; 

Variables Are Created When They Are Assigned a Value

You do not have to declare a variable before you use it. The first time a value is assigned to a variable, the variable is created and cast to the type of the value. PHP variables are also multitypes, in that they can contain data of different types at different times. For example:

 $myVariable = 5; $myVariable = 'hello world!'; 

The preceding lines are legal. The first makes $myVariable of an integer type and assigns it the value of 5. The second takes the same variable, clears out the old value, sets it to a string type, and assigns the text "hello world!" to it. PHP variables are whatever you need them to be.

PHP Supports Standard Data Types

The following data types are available in PHP: Integer, Float, String, Boolean, Array, and Object. The first four are consistent with most languages.

Arrays in PHP are declared with parentheses and can have either values or numbers as indices. Numbered indices count from 0 (zero).

A value index example:

 $myArray = array("favfruit"=>"apple", "favvegetable"=>"tomato"); echo $myArray[favfruit];    // writes the data "apple" 

A number index example:

 $myArray = array("apples", "oranges", "pears", "bananas"); echo $myArray[2];    // writes the data "pears" 

Object classes are declared with standard function-style syntax. You instantiate a class object using the keyword new.

Object example:

 class Hello {     function sayIt() {         echo 'hello world!';     } } $myGreeting = new Hello(); $myGreeting -> sayIt();    // writes the data "hello world!" 

PHP Supports Common Operators

PHP supports the standard operators commonly found in any language. The specific syntax of the operators might be slightly different than what you are familiar with, but simply review the following lists and you should have no problems.

Arithmetic operators include: +, -, *, /, and %. The % denotes a modulus operation. Examples of the operations are as follows:

 $a = 5; $b = 8; $c = 10; echo $a + $b;   // writes the data "13" echo $c - $b;   // writes the data "2" echo $a * $c;   // writes the data "50" echo $c / $a;   // writes the data "2" echo $b % $a;   // writes the data "3" 

String operators are limited to a simple concatenation using . (period) between the strings. For example:

 $a = 'hello'; $b = 'world'; $c = $a." ".$b; // sets $c to the value of $a plus a space plus $b. 

Tip

The parsing and subtraction of substrings from a variable is accomplished using function calls, such as substr(), substr_replace(), and trim().


The primary assignment operator that you should be familiar with is = (equals). There are assignment variants for every other operator type, but they always include the equals sign. Common examples include: +=, -=, *=, /=, %=, and .=.

Here are various operators in action:

 $a = 5;             // sets $a to the value 5 $a += 4;            // sets $a to the value of $a plus 4, now $a is 9 $a -= 3;            // sets $a to the value of $a minus 3. now $a is 6 $b = 'hello';       // sets $b to the value "hello" $b .= ' world!';    // sets $b to the value of $b plus " world", now $b is "hello world! " 

Comparison operators also follow standard C-style syntax. Table 19.1 illustrates the available operators and how they work.

Table 19.1. PHP Comparison Operators

OPERATOR

DESCRIPTION

EXAMPLE

RESULT

==

Equal

$a == $b

TRUE if $a is equal to $b

===

Identical

$a === $b

TRUE if $a is equal to $b, and they are of the same type

!=

Not equal

$a != $b

TRUE if $a is not equal to $b

!==

Not identical

$a !== $b

TRUE if $a is not equal to $b, or they are not of the same type

<

Less than

$a < $b

TRUE if $a is strictly less than $b

>

Greater than

$a > $b

TRUE if $a is strictly greater than $b

<=

Less or equal to

$a <= $b

TRUE if $a is less than or equal to $b

>=

Greater or equal to

$a >= $b

TRUE if $a is greater than or equal to $b


Logical PHP operators are also fairly standard. PHP also includes multiple ways to write the AND and OR operators. They are outlined in Table 19.2.

Table 19.2. PHP Logical Operators

OPERATOR

DESCRIPTION

EXAMPLE

RESULT

!

NOT

! $a

TRUE if $a is not TRUE

&&

AND

$a && $b

TRUE if both $a and $b are TRUE

and

AND

$a and $b

TRUE if both $a and $b are TRUE

||

OR

$a || $b

TRUE if either $a or $b is TRUE

or

OR

$a or $b

TRUE if either $a or $b is TRUE

xor

XOR

$a xor $b

TRUE if either $a or $b is TRUE, but not both


Writing Output

The standard method of writing output in PHP is the echo statement. echo is a language construct, and not a real function, so you are not required to use parentheses around the output. Here's an example of common output with and without variables:

 <?php echo 'hello world!'; $myVariable = 'hello world!'; echo $myVariable; ?> 

Single Variables Can Be Echoed with Shorthand

You can embed an echo into XHTML with a quick variable reference like so:

 <?php $letterCount = 4; ?> <p>The letter "s" appears in Mississippi <?=$letterCount?> times.</p> 

The embedded expression is equivalent to writing the same code this way:

 <?php $letterCount = 4; ?> <p>The letter "s" appears in Mississippi <?php echo $letterCount; ?> times.</p> 

The shorthand <?= ?> echo only works with single variables. If you want to output something more complex, you need to use the second method, or build the complex variable beforehand.

Single and Double Quote Differences

Strings contained inside double quotes are more dynamic than those using single quotes. Variables are not evaluated when they occur in single-quoted strings, and special characters/escape sequences are not rendered inside single quotes.

Note

The escape sequence \' that renders a single quote character is a special character and is evaluated correctly only from within single-quoted strings.


Examples of inline variables and quotes:

 <?php $dname = 'Fido'; echo "My dog is named $dName.";      // writes "My dog is named Fido." echo 'My dog is named $dName.';      // writes "My dog is named $dName." echo 'My dog is named '.$dName.'.';  // writes "My dog is named Fido." ?> 

Table 19.3 lists the escape sequences you can use with strings contained within double quotes.

Table 19.3. Escaped Characters for Double Quotes

SEQUENCE

DESCRIPTION

\n

New line

\r

Carriage return

\t

Tab

\\

Backslash

\$

Dollar sign

\"

Double quote


Use Double Quotes to Output Strings

The special characters can be rendered inside normal double-quoted strings very easily. In the following example, this code:

 <?php $cell1 = 'td-style1'; $title = 'Apples'; echo "<table cellspacing=\"0\" cellpadding=\"0\"><tr>\n"; echo "<td class=\"$cell1\">$title</td>\n</tr></table>"; ?> 

will write out this XHTML code:

 <table cellspacing="0" cellpadding="0"><tr> <td >Apples</td> </tr></table> 

Use Single Quotes to Output Strings

Single quotes can be just as useful in writing out XHTML because of all the required double quotes around tag attribute values. If you echo all your Hypertext Markup Language (HTML) inside double quotes, every quoted value will have to have its quotes escaped. You can see this in the preceding example.

Tip

Be careful when writing out single-quoted strings. Single quotes inside your test, such as apostrophes, need to be escaped.


When using single quotes around strings, the double quotes inside the string do not need to be escaped. This can make your XHTML more natural to read. Here is the same example, written with single quotes for the echo:

 <?php $cell1 = 'td-style1'; $title = 'Apples'; echo '<table cellspacing="0" cellpadding="0"><tr>'."\n"; echo '<td >'.$title.'</td>'."\n".'</tr></table>'; ?> 

There is an obvious gain whenever the XHTML is static, as seen in the first line, and there is a loss for single quotes when having to incorporate variables and escaped characters. What you choose to use should depend on the specific application, and you might find both together is the best solution overall.

Control Structures

PHP provides standard control structures as part of its syntax. They allow you to loop or branch through code based on tested conditions. The most common structures are if, for, while, and switch. The following are short examples of how each of the common control structures is laid out.

 <?php if ($a > $b) {    echo 'a is larger than b'; } elseif ($a == $b) {    echo 'a is equal to b'; } else {    echo 'a is smaller than b'; } for ($i = 1; $i <= 10; $i++) {    echo $i; } $i = 1; while ($i <= 10) {    echo $i++; } switch ($i) { case 0:    echo 'i equals 0';    break; case 1:    echo 'i equals 1';    break; case 2:    echo 'i equals 2';    break; } ?> 

Commenting in PHP

It's very important that you use comments within your code. There is the possibility that a different programmer will need to read your code later, but more likely you yourself will need to return to the code at a later date. Good comments can make all the difference in being able to follow a piece of code months after it's written.

There Are Different Kinds of Comments

There are three different kinds of comments supported in PHP: C, C++, and Unix shell comments. C-style comments allow you to block out multiple lines of code.

 <?php /* The following lines output the variable $myVariable. */ $myVariable = 'hello world!'; echo $myVariable; ?> 

C++ comments are for quick single-line comments. They affect a line from the comment marker to the end of the line. Code before the marker is rendered normally.

 <?php // The following lines output // the variable $myVariable. $myVariable = 'hello world!'; // $myVariable now has the value "hello world!" echo $myVariable; ?> 

Unix shell-style comments are seldom used inside code, but you might see their use in file headers, to block out the file description or copyright notice, for example. They work identically to the // syntax, but instead use a # (number sign). Shell comments are accomplished this way:

 <?php # The following lines output # the variable $myVariable. $myVariable = 'hello world!'; # $myVariable now has the value "hello world!" echo $myVariable; ?> 

The major standards groups generally discourage use of shell comments, and you should use the C++ single-line comments instead. They are covered here so you can easily recognize them if you come across shell comments in older code.

Use Comments with PostNuke Code

When editing PostNuke code, you should always use comments to save copies of the original code you are changing. If you have any problems and need to compare your change with the original, or simply turn your code off and reinstate the original, the source is already there waiting.

Comment lines inside the PostNuke source can also be used to mark your changes. Add a couple lines like these above or below your hacks:

 // ===================================================== // ===================================================== // ===================================================== 

Then when you are trying to find the spot where you changed the code, it's easy to see exactly where your edits begin. This is especially useful in the larger PostNuke files that can be well over a thousand lines of code.



    PostNuke Content Management
    PostNuke Content Management
    ISBN: 0672326868
    EAN: 2147483647
    Year: 2003
    Pages: 207
    Authors: Kevin Hatch

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net