PHP Syntax


For general PHP syntax, all statements are terminated with a semicolon ( ; ). In the PHP source code, any line starting with a double forward slash ( // ) signifies a comment, causing everything to the end of that line to be ignored by the PHP interpreter and by the HTML browser. For multiple-line comments, the comment line begins with a forward slash asterisk ( /* ) and ends, on another line, with an asterisk forward slash ( */ ). Everything in between that pair of tags will be considered a comment.

Note  

Comments are intended for documentation purposes and enable the programmer to insert reminders of the code s purpose.

Variables

PHP variables start with a dollar sign ( $ ), followed by either an underscore ( _ ) or a letter. After that, the variable can have any amount or combination of letters , numbers , or underscores. As in MySQL, a letter is defined as any lowercase or uppercase character a through z , as well as any character with an ASCII value of 127 to 255. Variables are case-sensitive; thus $ABC and $abc are different variables.

PHP variables are pseudo-typeless , which means that their types are determined by context. So, if a variable is assigned a string, it becomes a string type. However, variables may be cast ”forced to a certain type ”using this syntax:

 $s_string = set_type('string', $s_string); 

Or variables can be cast using the C-style syntax:

 $s_string = (string); 

Empty variables can be defined by the VAR statement when they are within a class construct for an object, but not when they are in free-standing procedural code:

 VAR $PHPvariable1; 

Variables can also be defined when they are used:

 $PHPvariable2="value2"; 

The data types of a PHP variable include INTEGER , FLOATING POINT , STRING , OBJECT , and ARRAY . If the type is not specifically defined, the variable is typed by the context in which it is used.

INTEGER Variables

The INTEGER is any whole number between “2 billion and +2 billion, using decimal, octal, or hexadecimal notation. For instance, all of the following variable definitions equal 100 in decimal, octal, and hexadecimal, respectively.

 $vdec=100; $voct=O144; $vhex=Ox64; 

FLOATING POINT Variables

The FLOATING POINT is a number with a decimal portion, in either decimal or scientific notation. FLOATING POINT variables are sometimes misleading, because values may not always be stored literally in a binary architecture; for instance, the fraction one-third cannot be precisely represented in binary. The following FLOATING POINT notations are for the same number in both decimal and scientific notations.

 $vfdec=1.23; $vfsci=123e1; 

STRING Variables

The STRING is any combination of letters, numbers, and/or special characters . When the STRING value is assigned to a STRING variable, the STRING value is surrounded by quotation marks (quotes). You can use either single quotes or double quotes, but you must be consistent, and there is a subtle difference. If single quotes surround the STRING , the assigned STRING value is exactly as it appears between the single quotes. If double quotes surround the STRING , the STRING is checked for any embedded PHP variables, and then those variables values are put into the code in place of the embedded variable name . The following variable examples show this difference:

 $vstring0 = "4"; $vstring1 = 'The value assigned is $vstring0' $vstring2 = "The value assigned is $vstring0" 

The value assigned to $vstring1 is The value assigned is $vstring0; the value assigned to $vstring2 is The value assigned is 4 , because the double quotes in the $vstring2 definition cause it to insert the assigned value of the variable $vstring0 .

You may need to include special characters in a quoted STRING . To achieve this, you use the backslash ( \ ), which is the escape character, to indicate that the following special character is to be interpreted literally, without any substitution that it might normally indicate :

 $vstring3 = 'The value assigned is \"ESCAPE\"' 

The value assigned to the PHP variable $vstring3 is The value assigned is "ESCAPE" . The backslashes allow the double quotes to be shown, instead of interpreted as STRING indicators. Common escape sequences for special characters are listed in Table C-1.

Table C-1: Escape Sequence Meanings

Escape Sequence

Meaning

\n Start a new line

\r

Insert a carriage return

\t

Insert a tab character

\\

Print a backslash character

\"

Print a double quote within a string

\$

Print a dollar sign

\0 ( zero)

Print an octal value

\x

Print a hexadecimal value

Note  

Escape characters work when printing to the display or to a file, but they do not work correctly when printing to HTML for viewing through a browser. In this case, you must use HTML format tags, such as the < BR > tag for a new line.

ARRAY Variables

An ARRAY variable is a single name that can reference a set of values by using the array name and an index. PHP has two types of arrays: anonymous (an integer index) and hash key (some string that can be used as an index). A simple example of an anonymous array that initializes an ARRAY variable named $varray with four values follows :

 $varray = array("value1", "value2", "value3","value4"); 

Indexes start at zero, so $varray[0] has the value value1 and $varray[3] has the value value4 . In addition, the ARRAY can be expanded by assigning new values. The value is added after the last array entry.

 $varray[ ] = "value5"; 

Here is an example of a hash key array:

 $vhash = array ('size' => 'medium', 'color' => 'blue', 'temp' =>  'warm); 

OBJECT Variables

An OBJECT is an instance of a class. To create an OBJECT , a class must first exist. The following is a trivial example using PHP to define the class with a member variable and two class functions: one to set the value and one to retrieve the value. Member values are typically not accessed directly. PHP creates the variable $this , which is available anywhere within the class to reference a created object itself.

Note  

This example uses a special form of comments called PHPDoc , which is used in many PHP object-oriented code projects. It is very similar in syntax to JDoc and is highly recommended when writing code for large projects.

 <?php    class php_object       {       var $php_var; //This is called a constructor // Constructors have the same name as the class // in PHP4.  This constructor initialized our // variable to null.       function php_object()          {          $this->php_var = null;          } // getvar() returns our variable       function getvar()          {          return $this->php_var;          } // setvar() sets our variable       function setvar($setvalue)          {          $this->php_var = $setvalue;          }       } ?> 

You can create a new OBJECT or instance of the php_object class with the following PHP code. The $a_php_object variable keeps the reference to the new OBJECT .

 <?php    $a_phpobject =& new php_object(); ?> 

Any variable or function in the OBJECT can now be accessed, as the following example shows:

 <?php    $a_phpobject->setvar(4);    echo $a_phpobject->getvar(); ?> 

OBJECT member variables are typically not accessed directly. The setvar class function call with the new object will assign the $a_phpobject object s php_var variable to the value 4 . The getvar class function will fetch the value of the $a_phpobject object s php_var variable for the PHP ECHO command to display.

The PHP PRINT and ECHO commands achieve the same basic result: they produce output on the screen. There is, however, one slight difference: The PRINT command can return a TRUE/FALSE result, whereas the ECHO command cannot. Because of this minor difference, the ECHO command is sometimes said to be slightly faster.

PHP variable data types can change from one assignment operation to the next , a characteristic referred to as loosely typed . To control the data type of an assignment, PHP supports the concept of typecasting. When a variable is assigned a value, a data type can also be specified. This data type can be different from that of the source data type. The target type appears within parentheses after the equal sign with one of the following values: ( INT ), ( ARRAY ), ( OBJECT ), ( STRING ), ( REAL ), ( DOUBLE ), or ( FLOAT ). The following example resets the data type of the already assigned variable $vinteger to an INTEGER rather than the REAL value of its source.

 $vinteger = (int) $vreal ; 

This can also be accomplished using the settype function:

 $vinteger = $vreal; settype($vinteger, 'integer'); 

Operators

PHP supports familiar operators, including arithmetic, logical, concatenation, and comparison operators.

Arithmetic Operators

The following are some of the common arithmetic operators.

Arithmetic Operator Example

Explanation

$a + $b

Adds variables $a and $b

$a - $b

Subtracts variable $b from $a

$a * $b

Multiplies $a and $b

$a / $b

Divides $a by $b

$a % $b

Returns modulus (remainder) of $a divided by $b

Logical Operators

Logical operators evaluate values and determine whether they are true or false according to the specified criteria. The following are some examples.

Logical Operator Example

Explanation

$a and $b$a && $b

AND operation means both values must be true.

$a or $b$a $b

OR operation means one or the other value must be true.

Not $a! $a

NOT operation means the value cannot be true.

Concatenation Operator

The concatenation operator takes two string values and combines them, in the specified order, into one string value. For example, $a.$b concatenate the text values of variable $a with that of $b .

Comparison Operators

Comparison operators determine the relationship between two variables or expressions and return TRUE or FALSE . The following are some examples.

Comparison Operator Example

Explanation

$a < $b

Less than: if $a < $b , then the result is TRUE; otherwise it s FALSE

$a > $b

Greater than: if $a > $b , then the result is TRUE; otherwise it s FALSE

$a < = $b

Less or equal: if $a < = $b , then the result is TRUE; otherwise it s FALSE

$a > = $b

Greater or equal: if $a > = $b , then the result is TRUE; otherwise it s FALSE

!$a

NOT: negate the logical TRUE/FALSE value of $a

$a == $b

Equality: if $a and $b are equal, then TRUE; otherwise FALSE

Operator Precedence

Operators have precedence levels. That means that there is an order in which PHP deals with them, some getting preferential consideration over others.

All operations at the same precedence level can be completed in any sequence without changing the result. Addition and subtraction, for instance, are at the same precedence level. When both addition and subtraction occur, the operations are performed in order of their appearance in an expression. Similarly, multiplication and division are at the same level.

When operations of different precedence are in the same expression, all operations of a higher precedence are done before those of a lower precedence, regardless of their order of appearance. Multiplication and division are done before any addition or subtraction.

You can use parentheses to override or impose a desired sequence of operator processing. Parentheses are also useful to document and clarify the sequence of calculation in an expression.

Table C-2 gives more detail about operators and the operator precedence in PHP.

Table C-2: Operators, with Their Precedence and Description

Precedence
Level

Operator

Description

Evaluation Sequence (R=Right; L=Left)

1

new

Create new object

R to L

2

.

Property access (dot notation)

L to R

2

[ ]

Array index

L to R

2

( )

Function call

L to R

3

!

Logical NOT

R to L

3

~

Bitwise NOT

R to L

3

++ , --

Increment and decrement operators

R to L

3

+ , -

Unary plus and negation

R to L

3

(int) , (double) , (string) , (array) , (object)

Cast operators

R to L

3

@@

Inhibit errors

R to L

4

* , / , %

Multiplication, division, modulo (remainder)

L to R

5

+ , -

Addition, subtraction

L to R

5

.

Concatenation

L to R

6

<<, >>

Bitwise-shift left, bitwise-shift right

L to R

7

<, < = , >, > =

Comparison operators: less than, less than or equal to, greater than, greater than or equal to

L to R

8

== , !=

Equality, inequality

L to R

8

=== , !==

Identity, nonidentity

L to R

9

&

Bitwise AND

L to R

10

^

Bitwise XOR

L to R

11

Bitwise OR

L to R

12

&&

Logical AND

L to R

13

Logical OR

L to R

14

? :

Conditional (ternary)

R to L

15

=

Assignment

R to L

15

*= , /= , %= , += , -=

Assignment with operation

R to L

16

and

Logical AND

L to R

17

xor

Logical XOR

L to R

18

or

Logical OR

L to R

19

,

List separator

L to R

Functions

Functions are traditional language constructs that allow repeated tasks to be defined with customized parameters and to return the results to the point of the function call in the program s logic. PHP supports user -defined functions, as well as many standard-language functions.

User-Defined Functions

When you have a series of commands that you are going to perform repeatedly, you can choose to turn those commands into a function. This means that instead of typing in multiple lines of code whenever you need to achieve that result, you need to type those lines only once (in the function definition), and then you put the much shorter function call into your code wherever you need it. PHP allows users to create customized functions using the following syntax:

 function <  function_name  >(<  function_parameters  >) {    (<  PHP_function_code  >) } 

Built-in Functions

Built-in functions are repeatedly used pieces of code that have already been written and tested . Instead of typing multiple lines of code to accomplish a commonly executed task, you call the function by using its name and parameters. For a list of the built-in PHP functions and examples of their use, refer to http://www.php.net/manual/en/funcref.php.

Some built-in functions are so common that they are often thought to be part of the command syntax. ECHO , for instance, is actually a built-in function that takes its input text and places it in the HTML at the current location, but it is so commonly used that most users assume it is part of the command syntax.

Control Structures

Most languages assume the sequential flow from one statement to the next unless some language-dependent control structure imposes a change. PHP supports a number of common control structures, such as IF , WHILE , FOR , SELECT , and some variations.

IF/IFELSE Control Structures

One variation of the IF conditional control structure is the IFELSE extension, which allows several return conditions to result in actions that are specified for each unique return, one of which is executed at the same point of the program logic flow.

The following is the basic syntax for an IFELSE control structure:

 <?php    if (<  expression1  )       {       <  statement1  >;       }    elseif (<  expression2  >)       {       <  statement2  >;       }    else       {       <  statement_default  >;       } ?> 

You use an IFELSE keyword to define blocks of statements, as well as the precedence order of the condition expression associated with the block of code. A single statement or block of statements is executed if its specified condition is true and all previous condition expressions were false. If all condition expressions are false, the default statement after the ELSE keyword is executed. In other words, the series of IF conditions is evaluated one after another, and the first one of them that evaluates as true sends the program s path to its block of statements. If none of the IF conditions evaluate to true, the logic path falls all the way through, and the ELSE statements are executed.

WHILE Control Structures

The WHILE construct is a loop that allows a block of code to be repeated until some condition is satisfied. The syntax for the basic WHILE control structure is as follows:

 <?php    while (<  condition  >):       (<  PHP_statements  >)    endwhile; ?> 

The condition is tested at the beginning of the WHILE block, and if it evaluates to true, the block of code it contains is executed. Otherwise, it proceeds through the WHILE loop until it reaches the end. At the end of each loop through the block of code, the condition is tested again to see if it is still true and if it should continue with another iteration, or if it is now false and should exit to the statement that follows the WHILE loop. The condition expression might evaluate to false in the middle of the code block, but even if it does, the execution will continue until the test at the end of the code block.

FOR and FOREACH Control Structures

The FOR control structure loops through a block of code for some specified number of iterations. An index variable is frequently used so that it can get its initial value, and then increment with each iteration, which is compared with an exit value. The basic syntax appears simple, but the logic expressed within this control structure can be very complex:

 <?php    for (  expression1;   expression2;   expression3  )       {       (<  PHP_statements  >)       } ?> 

In a FOR control structure, the three expressions are as follows:

  • The first expression is the starting value for the loop counter.

  • The second expression is the evaluation criteria that the loop counter is compared against.

  • The third expression is the incremental increase for the loop counter.

So, the block of code within the loop, in this case one or more PHP commands, is executed until expression1 has been incremented by the definition in expression3 and meets the evaluation criteria used for comparison in expression2 . In other words, it allows you to specify exactly how many times a particular block of code is executed.

The FOREACH control structure is a common variation of the FOR loop and is especially useful for iterating through arrays. It can be run for anonymous arrays or array hashes. Here is an example for an anonymous array:

 <?php    foreach ($array as $value)       {       (<PHP code>)       } ?> 

And here is an example of the FOREACH structure to iterate through a hash array:

 <?php    foreach ($hash as $key => $value)       {       (<PHP code>)       } ?> 

SWITCH Control Structures

The SWITCH control structure allows you to map out several paths that branch from a single place in your code, allowing you to choose one path depending on the circumstances. The SWITCH control structure has the following syntax:

 <?php switch (<  expression  >)    {    case <  value1  >:       <  block_of_code_1  >;       break;    case <  value2  >:       <  block_of_code_2  >;       break;    <  as_many_CASE_values_as_needed  >    default:    <  statement_default  >;    } ?> 

A specific expression is hard-coded into the program, and the value of that expression is compared to any number of other values defined as CASE statements. Each CASE statement has its own corresponding block of code, which may be one or more lines of code. If the expression matches a particular CASE value, that CASE value s code is executed. Once the BREAK at the end of that block of code is reached, the SWITCH control structure is finished, and the program continues. If the expression does not equal any of the CASE values, it falls through the code and either proceeds without executing any code or executes the default block of code if one is defined.

Using a BREAK at the end of each CASE will terminate the SWITCH after a successful match of the CASE value with the expression. If a BREAK is not included, the SWITCH will continue executing all statements until the end of the SWITCH . This means that the default, if one were defined, would always be executed; so unless that is your intention , remember to insert a BREAK at the end of each CASE block of code.




MySQL(c) Essential Skills
MySQL: Essential Skills
ISBN: 0072255137
EAN: 2147483647
Year: 2006
Pages: 109

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