PHP control statements

Source: Internet
Author: User

1. If statement

If statements are an important feature of most languages. They are executed based on conditions.Program. PHP's If statement is similar to C:

If (expr)

Statement

As discussed in the expression, expr is calculated as its true value. If expr is true, PHP executes the corresponding statement. If it is false, ignore it.

If $ A is greater than $ B, the following example shows \ 'a is bigger than B \':

If ($ A> $ B)

Print \ "A is bigger than B \";

Generally, you want to execute more than one statement according to the condition. Of course, you do not need to add If judgment to each statement. Instead, you can combine multiple statements into a statement group.
If statements can be nested in other if statements, allowing you to flexibly execute various parts of the program with conditions.

2. Else statements

Generally, you want to execute a statement when the specified conditions are met. If the conditions are not met, execute another statement. Else is used to do this. Else extends the if statement and executes another statement when the if statement expression is false. For example, if $ A is greater than $ B, \ 'a is bigger than B \ 'is displayed. Otherwise, \ 'a is not bigger than B \' is displayed \':

If ($ A> $ B ){
Print \ "A is bigger than B \";
}
Else {
Print \ "A is not bigger than B \";
}

3. elseif statement

Elseif, as shown in the name, is a combination of IF and Else, similar to else. It extends the if statement to execute other statements when the if expression is false. But unlike Else, it only executes other statements when the elseif expression is true.

Multiple elseif statements can be used in one If statement. The first statement with the elseif expression true will be executed. In PHP 3, you can also write \ 'else if \ '(two words) and \ 'elseif \' (one word. This is just a small difference in writing (if you are familiar with C, it is also), the results are exactly the same.

The elseif statement is executed only when the if expression and any earlier elseif expression are both false and the current elseif expression is true.
The following is an if statement containing the nested formats of elseif and else:

If ($ A = 5 ):
Print \ "A equals 5 \";
Print \"...\";
Elseif ($ A = 6 ):
Print \ "A equals 6 \";
Print \"!!! \";
Else:
Print \ "A is neither 5 nor 6 \";
Endif;

4. While statement

While loop is a simple loop of PHP 3. As in C. The basic format of the while statement is:

While (expr) Statement

The while statement is very simple. It tells PHP to repeatedly execute nested statements as long as the while expression is true. Check the value of the while expression at the beginning of each loop. Therefore, this execution will not terminate even if its value is changed in the nested statement, and until the loop ends (every time PHP runs a nested statement, it is called a loop ). Similar to the IF statement, you can enclose a group of statements in braces and execute multiple statements in the same while loop:

While (expr): Statement... endwhile;

In the following example, all numbers are 1 to 10:

/* Example 1 */
$ I = 1;
While ($ I <= 10 ){
Print $ I ++;/* The printed value wocould be $ I before the increment (post-
Increment )*/
}

/* Example 2 */
$ I = 1;
While ($ I <= 10 ):
Print $ I;
$ I ++;
Endwhile;

5. Do... while statement

Do... while is very similar to a while loop, but it checks whether the expression is true at the end of each loop, rather than at the beginning of the loop. The main difference between it and the strict while loop is do .. the first loop of while must be executed (the true value expression is only checked at the end time of the loop), instead of strictly executing the while loop (check the true value expression at the beginning of each loop, if it is set to false at the beginning, the execution will be terminated immediately ).

Do... while loop only has one form:

$ I = 0;
Do {
Print $ I;
} While ($ I> 0 );

The preceding loop is executed only once, because after the first loop, when the true value expression is checked, it is calculated as false ($ I is not greater than 0) and the loop is terminated.

6. For Loop statements

A For Loop is the most complex loop in PHP. As in C. The syntax of the For Loop is:

For (expr1; expr2; expr3) Statement

The first expression (expr1) is unconditionally calculated (executed) at the beginning of the loop ).
The expression expr2 is calculated for each loop. If the result is true, the loop and nested statements continue to be executed. If the result is false, the entire loop is closed.
At the end of each loop, expr3 is calculated (executed). Each expression can be empty. If expr2 is null, the number of cycles is not fixed (PhP defaults to true, like C ). Do not end the loop unless you use a break statement to replace the true value expression of.
Consider the following example. They all show numbers 1 to 10:

/* Example 1 */
For ($ I = 1; $ I <= 10; $ I ++ ){
Print $ I;
}

/* Example 2 */
For ($ I = 1; $ I ++ ){
If ($ I> 10 ){
Break;
}
Print $ I;
}

/* Example 3 */
$ I = 1;
For (;;){
If ($ I> 10 ){
Break;
}
Print $ I;
$ I ++;
}

Of course, the first example is obviously the best, but you can find that in the for loop, you can use an empty expression in many cases.
In other languages, a foreach statement is used to traverse an array or hash table. PHP uses the while statement, list (), and each () functions to achieve this function.

7. Switch selection statement

The switch statement is like a series of IF Statements for the same expression. In many cases, you want to compare the same variable (or expression) with many different values and execute different program segments based on different comparison results. This is the use of the switch statement.

The following two examples use different methods to do the same thing. One uses a group of if statements and the other uses a switch statement:

/* Example 1 */
If ($ I = 0 ){
Print \ "I equals 0 \";
}
If ($ I = 1 ){
Print \ "I equals 1 \";
}
If ($ I = 2 ){
Print \ "I equals 2 \";
}

/* Example 2 */
Switch ($ I ){
Case 0:
Print \ "I equals 0 \";
Break;
Case 1:
Print \ "I equals 1 \";
Break;
Case 2:
Print \ "I equals 2 \";
Break;
}

(2) require statement

The require statement replaces itself with the specified file, which is similar to the preprocessing # include in C.
This means that you cannot put the require () statement in a loop structure to call this function every time to contain the content of different files ,. To do this, use the include statement.

Require (\ 'header. inc \');

(3) include statements

The include statement contains the specified file.
Each time an Include statement is run, it contains the specified file. Therefore, you can use the include statement in a loop structure to include a series of different files.

$ Files = array (\ 'first. inc \ ', \ 'Second. inc \', \ 'Third. inc \');
For ($ I = 0; $ I <count ($ files); $ I ++ ){
Include ($ files [$ I]);
}

(4) Functions

You can use the following syntax to define a function:

Function Foo ($ arg_1, $ arg_2,..., $ arg_n ){
Echo \ "example function. \ n \";
Return $ retval;
}

Function can use any valid php3Code, Or even the definition of other functions or classes

1. function return value

Functions can return values through optional return statements. The return value can be of any type, including list and object.

Function my_sqrt ($ num ){
Return $ num * $ num;
}
Echo my_sqrt (4); // outputs \ '16 \'.

The function cannot return multiple values at the same time, but it can be implemented by returning the list:

Function Foo (){
Return array (0, 1, 2 );
}
List ($ zero, $ one, $ two) = Foo ();

2. Parameters

External information can be passed into the function through the parameter table. The parameter table is a series of variables and/or constants separated by commas.
Php3 supports parameter (default), variable parameter, and default parameter. Variable-length parameter tables are not supported, but can be implemented by transmitting arrays.

3. Associated Parameters

Function parameters are passed by default. If you allow the function to modify the value of the input parameter, you can use the variable parameter.
If you want a form parameter of a function to always be a variable parameter, you can add the (&) prefix to the form parameter during Function Definition:

Function Foo (& $ bar ){
$ Bar. = \ 'and something extra .\';
}
$ STR = \ 'this is a string ,\';
Foo ($ Str );
Echo $ STR; // outputs \ 'this is a string, and something extra .\'

If you want to pass a variable parameter to the default function (its form parameter is not the variable parameter method), you can add the (&) prefix to the actual parameter when calling the function:

Function Foo ($ bar ){
$ Bar. = \ 'and something extra .\';
}
$ STR = \ 'this is a string ,\';
Foo ($ Str );
Echo $ STR; // outputs \ 'this is a string ,\'
Foo (& $ Str );
Echo $ STR; // outputs \ 'this is a string, and something extra .\'

4. Default Value

The function can define the default values of the C ++ style, as follows:

Function makecoffee ($ type = \ "cappucino \"){
Echo \ "making a cup of $ type. \ n \";
}
Echo makecoffee ();
Echo makecoffee (\ "Espresso \");

The output of the above Code is:

Making a cup of cappucino.
Making a cup of espresso.
Note: When Using default parameters, all parameters with default values should be defined behind those with no default values; otherwise, they will not work as expected.

5. Class)

A class is a collection of variables and functions. Class is defined using the following syntax:

<? PHP
Class cart {
VaR $ items; // items in our shopping cart
// Add $ num articles of $ artnr to the cart
Function add_item ($ artnr, $ num ){
$ This-> items [$ artnr] + = $ num;
}
// Take $ num articles of $ artnr out of the cart
Function remove_item ($ artnr, $ num ){
If ($ this-> items [$ artnr]> $ num ){
$ This-> items [$ artnr]-= $ num;
Return true;
} Else {
Return false;
}
}
}
?>

The above defines a class named cart, which includes an associated array and two functions used to add and delete projects from cart.
Class is the original model of the actual variable. You need to use the new operator to create a variable of the desired type.

$ Cart = new cart;
$ Cart-> add_item (\ "10 \", 1 );

This creates a cart Class Object $ cart. The add_item () function of this object is called to add 1 to the first item.

Class can be expanded from other classes. The expanded or derived class has all the variables and functions of the base class and what you define in the extended definition. This requires the extends keyword.

Class named_cart extends cart {
VaR $ owner;
Function set_owner ($ name ){
$ This-> owner = $ name;
}
}

A class named named_cart is defined here. It inherits all variables and functions of the cart class and adds a variable $ owner and a function set_owner (). The named_cart variable you created can now set the owner of carts. In the named_cart variable, you can still use the general cart function:

$ Ncart = new named_cart; // create a named cart
$ Ncart-> set_owner (\ "Kris \"); // name that cart
Print $ ncart-> owner; // print the cart owners name
$ Ncart-> add_item (\ "10 \", 1); // (inherited functionality from cart)

The variable $ this in the function indicates the current object. You need to use $ this-> something to access all the variables or functions of the current object.
Class constructor is a function automatically called when you create a new variable of a certain type. A function with the same name as a class is the constructor.

Class auto_cart extends cart {
Function auto_cart (){
$ This-> add_item (\ "10 \", 1 );
}
}

Here we define a class auto_cart, which adds a constructor for the cart class to set project 10 for variable initialization every new operation. The constructor can also have parameters, which are optional. This feature makes it very useful.

Class constructor_cart {
Function constructor_cart ($ item = \ "10 \", $ num = 1 ){
$ This-> add_item ($ item, $ num );
}
}
// Shop the same old boring stuff.
$ Default_cart = new constructor_cart;
// Shop for real...
$ Different_cart = new constructor_cart (\ "20 \", 17 );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.