Chapter V.4. PHP

In the old days, Web pages were used to display information, such as text and graphics. Nowadays, Web pages are dynamic, so they not only need to respond to the user, but they often need to retrieve information off a Web page and store it in a database, such as when you type your credit card number to buy something off a Web site.

HTML can create simple user interfaces, but when you need to transfer data from a Web page to another program, such as a database, you need to use a programming language. Although programmers have used C, Perl, and Java to link Web pages to other programs like databases, one of the most popular programming languages for this task is PHP, which is a recursive name that stands for PHP Hypertext Processor (www.php.net).

Although languages such as C and Perl can be used to create standalone applications, PHP programs are unique in that they can run only on Web pages. Not only is PHP designed for creating programs within Web pages, but PHP is also free and capable of running under many different operating systems. If you're already familiar with C and Perl, you'll find that PHP mimics much of the syntax from both languages. Although you can create dynamic Web sites with other programming languages, you may find PHP easier and simpler to use.

The Structure of a PHP Program

At the simplest level, a PHP program can consist of one or more commands embedded in a Web page's HTML code, such as

<html>
  <body>
    <?php
      echo "<h1>Greetings from PHP.</h1>";
?>
  </body>
</html>

The <?php and ?> tags define the beginning and ending of a PHP program. PHP programs (scripts) are usually stored in a file that ends with the .php file extension.

Creating Comments

To write a comment in PHP, you have three choices: //, #, or /* and */ symbols. Both the double slash (// ) and the number (# ) characters are used to create comments on a single line, such as

<html>
  <body>

  // This is the beginning of the PHP program.

    <?php
      echo "<h1>PHP is a unique Web-specific language</h1>";
    ?>
  # This is the end of the PHP program

  </body>
</html>

If you want to write a comment over multiple line, use the /* and the */ characters, such as

<html>
  <body>

  /* This is the beginning of the PHP program.
     If a comment extends over multiple lines,
     It's easier to use these types of comment
     symbols instead. */

    <?php
     echo "<h1>PHP can be fun and profitable</h1>";
    ?>
  </body>
</html>

Declaring Variables

PHP variables can hold any type of data, so a variable might hold a string one moment and a number the next. To declare a variable in PHP, you must begin every variable name with the dollar symbol ($), such as

$VariableName = value;

VariableName can be any descriptive name, but PHP is a case-sensitive language so $MyAge is considered a completely different variable from $myage. Some programmers use uppercase letters to make variable names easier to find, and others use all lowercase.

One unique feature of PHP is its ability to reference the same value. For example, consider the following code:

$myage = 35;
$yourage = $myage;
$myage = 109;

In this example, the $myage variable is initially set to 35 and the $yourage variable is set to the $myage variable, which means the $yourage variable also contains the value of 35 . The third line stores the value 109 into the $myage variable, but the $yourage variable still holds the value of 35.

By referencing variables with the ampersand symbol (&), PHP allows a variable to contain identical data without specifically assigning those values. For example:

$myage = 35;
$yourage = &$myage;
$myage = 109;

The second line in the preceding PHP code tells the computer that the $yourage variable references the $myage variable, so whatever value the $myage variable contains from now on will automatically get stored in the $yourage variable.

After the third line, the $myage variable now contains the value of 109, so the $yourage variable contains 109 too.

Using Operators

The three types of operators used in PHP are mathematical, relational, and logical operators.

Mathematical operators calculate numeric results such as adding, multiplying, or dividing numbers, as shown in Table 4-1.

Table V.4-1. Mathematical Operators

Mathematical Operator

Purpose

Example

+

Addition

5 + 3.4

-

Subtraction

203.9 - 9.12

*

Multiplication

39 * 146.7

/

Division

45 / 8.41

%

Modula division (returns the remainder)

35 % 9 = 8

Relational operators compare two values and return a True or False value. The seven comparison operators available are shown in Table 4-2.

Table V.4-2. Relational Operators

Relational Operator

Purpose

==

Equal

===

Identical

!= or <>

Not equal

<

Less than

<=

Less than or equal to

>

Greater than

>=

Greater than or equal to

Warning

PHP uses three equal signs (===) to compare to values and determine if they are of the same data type. For example, PHP treats 14.0 and 14 as identical because both are numbers, but 14.0 and "14.0" wouldn't be considered equal because one is a number and the other is a different data type (a string).

Logical operators compare two Boolean values (True or False) and return a single True or False value, as shown in Table 4-3.

Table V.4-3. Logical operators

Logical Operator

Truth Table

&& (AND)

True && True = True

True && False = False

False && True = False

False && False = False

|| (OR)

True || True = True

True || False = True

False || True = True

False || False = False

XOR

True XOR True = False

True XOR False = True

False XOR True = True

False XOR False = False

!

!True = False

!False = True

Increment and decrement operators

PHP has a special increment (++) and a decrement (--) operator, which simply adds or subtracts 1 to a variable. Typically, adding 1 to a variable looks like this:

j = 5;
i = j + 1;

The increment operator replaces the + 1 portion with ++, such as

j = 5;
i = ++j;

In the preceding example, the value of i is j + 1 or 6, and the value of j is also 6.

Warning

If you place the increment operator after the variable, such as

j = 5;
i = j++;

Now the value of i is 5, but the value of j is 6.

The decrement operator works the same way except that it subtracts 1 from a variable, such as

j = 5;
i = --j;

In the preceding example, the value of i is j - 1 or 4, and the value of j is also 4.

Warning

If you place the decrement operator after the variable, such as

j = 5;
i = j--;

Now the value of i is 5, but the value of j is 4.

Assignment operators

Most programming languages use the equal sign to assign values to variables, such as

i = 59;

However, PHP also include combination assignment and mathematical operators, as shown in Table 4-4.

Table V.4-4. Assignment Operators

Assignment Operator

Purpose

Example

+=

Addition assignment

i += 7 (equivalent to i = i + 7)

-=

Subtraction assignment

i -= 4 (equivalent to i = i - 4)

*=

Multiplication assignment

i *= y (equivalent to i = i * y)

/=

Division assignment

i /= 3.5 (equivalent to i = i / 35)

%=

Modulo assignment

i %= 2.8 (equivalent to i = i % 2.8)

Branching Statements

The simplest branching statement is an IF statement that runs only one or more commands if a Boolean condition is True, such as

if (condition) {
  Command;
  }

To make the computer choose between two mutually exclusive sets of commands, you can use an IF-ELSE statement, such as

if (condition) {
  Command;
  }
else {
Command;
  }

Although the IF-ELSE statement can only give the computer a choice of two groups of commands to run, the IF-ELSEIF statement can offer the computer multiple groups of commands to run, such as

if (condition1) {
  Command;
  }
elseif (condition2) {
  Command;
  }
elseif (condition3) {
  Command;
  }

As an alternative to the IF-ELSEIF statement, you can also use the SWITCH statement to offer two or more choices, such as

switch (expression) {
case value1:
  Command;
  break;
case value2:
  Command;
  break;
default:
  Command;
}

Warning

The SWITCH statement always needs to include the break command to tell the computer when to exit out of the SWITCH statement.

The preceding SWITCH statement is equivalent to the following IF-ELSE statement:

if (expression == value1) {
  Command;
  }
elseif (expression == value2) {
  Command;
  }
else {
  Command;
  }

To check if a variable matches multiple values, you can stack multiple case statements, such as

switch (expression) {
case value1:
case value2:
  Command;
  break;
case value3:
case value4;
  Command;
  break;
default:
  Command;
}

The preceding SWITCH statement is equivalent to the following IF-ELSE statement:

if (expression == value1) || (expression == value2) {
  Command;
  }
else if (expression == value3) || (expression == value4) {
  Command;
  }
else {
  Command;
  }

Looping Statements

A looping statement repeats one or more commands for a fixed number of times or until a certain Boolean condition becomes True. To create a loop that repeats for a fixed number of times, use the FOR loop, which looks like this:

for (startvalue; endvalue; increment) {
  Command;
}

If you wanted the FOR loop to run four times, you could set the Start value to 1 and the End value to 4, such as

for ($i = 1; $i <= 4; $i++) {
  Command;
  }

If you don't know how many times you need to repeat commands, use a WHILE loop, which looks like this:

while (condition) {
  Command;
}

If the condition is True, the loop runs at least once. If this condition is False, the loop doesn't run.

Warning

Somewhere inside a WHILE loop, you must have a command that can change the condition from True to False; otherwise the loop will never end and your program will appear to hang or freeze.

Creating Functions

To break up programming problems, you can create subprograms that solve a specific task. Such subprograms are functions. The format of a typical function looks like this:

function functionname (Parameter list)
  {
  Commands;
  return $value;
  }

The two parts of a PHP function are

Parameter list: Defines any data that the function needs to work. If the function doesn't need to accept any values, the parameter list can be empty.

Return: Defines a value to return.

If a function doesn't return a value or accept any parameters, it might look like this:

function myfunction ()
  {
  Command;
  }

using Arrys

PHP creates arrays that can hold any type of data and grow as large as you need them without having to define a size ahead of time. To create an array, define an array name, the data you want to store, and the index number where you want to store that item in the array like this:

$arrayname[index] = data;

So if you wanted to store the string "Hello" and the number 4.23 in the first and second elements of an array, you could do the following:

$myarray[0] = "Hello";
$myarray[1] = 4.23;

For greater flexibility in retrieving data, PHP lets you create associative arrays, which let you identify data by a unique string (called a key) rather than an arbitrary index number. Instead of assigning data to a specific index number, you assign data to a unique string, such as

$arrayname["key"] = data;

If you wanted to assign the number 3.14 to the "pi" key, you'd do this:

$myarray["pi"] = 3.14;

To retrieve data from an associative array, use the key value, such as

$variable = $arrayname["key"];

So if you wanted to retrieve data stored under the key "pi", you could do the following:

$myarray["pi"] = 3.14;
$number2use = $myarray["pi"];

The first line stores the value 3.14 into the array and assigns it to the key "pi" . The second line yanks out the data, associated with the key "pi", and stores that data into the $number2use variable.

Warning

PHP includes a library of built-in array functions for manipulating arrays such as array_pop (which removes the last element from an array), array_push (which adds an element to the end of an array, and sort (which sorts arrays in ascending order).

Creating Objects

PHP supports object-oriented programming. To create an object, you must define a class, which specifies the properties and methods, such as

class classname {
  public $propertyname;

  public function methodname() {
    commands;
  }
}

To create an object, you must use the following syntax:

$objectname = new classname;

To assign a value to an object's property, specify the object name and the property you want to use, such as

$objectname->propertyname = value;

When assigning a value to an object's property, notice that the dollar symbol ($) isn't used to designate the property name.

To tell an object to run a method, specify the object name followed by the method name, such as

$objectname->methodname();

PHP allows single inheritance where an object can inherit from one class (in contrast to multiple inheritance, which allows an object to inherit from two or more classes). To inherit from a class, use the extends keyword followed by the class name you want to inherit from, such as

class classname1 {
  public $propertyname;

  public function methodname() {
    commands;
  }
}
class classname2 extends classname1 {
  public $propertyname;

  public function methodname() {
    commands;
  }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset