Process control and implementation methods in PHP speech

Source: Internet
Author: User
: This article mainly introduces the process control and implementation methods in PHP speech. if you are interested in PHP tutorials, please refer to them. A script is composed of statements. statements are implemented by flow control. This section describes the use of several keywords.

Elseif

elseifAndelse ifThe behavior is exactly the same. if you use a colon to defineif/elseifCondition, you cannot use two words.else ifOtherwise, PHP will produce a parsing error.


   $b) :echo"$a is greater than $b";elseif($a == $b) :echo"$a equals $b";else :echo"$a is neither greater than or equal to $b";endif;

Alternative syntax

The following keywords can use the alternative syntax of flow control. The basic form is to replace left curly braces with colons, and right curly braces with the following characters.

if - endifwhile - endwhilefor - endforforeach - endforeachswitch - endswitch

Note! PHP does not support mixing two syntaxes in the same control block.

Do-while

This loop seems familiar, but ignores some of its usage.

As stated in the manual, senior C language users may be familiar with another differentdo-whileLoop usage, put the statement indo-while(0). I have heard of this kind of technique for the first time. it seems that I am still a little white in C language.

Search and sort it out.do-while(0)Advantages of this special usage.

  1. Code chunks are more intuitive than just curly braces.
  2. UsebreakSkip the remaining code.
  3. It is helpful for macro-defined functions. when using a function, you can add points at the end of a sentence, which looks more like a function call.
  4. Block-level scope to prevent variable names from spreading to the upper-level scope.
  5. DeformedgotoStatement.

This post is quite good. The role of do {} while (0)-c ++-SegmentFault.

Foreach

foreachIt can only be applied to the traversal of arrays and objects.foreachThe syntax structure provides a simple way to traverse arrays. There are two types of syntax.

foreach(array_expression as$value)statementforeach(array_expression as$key => $value)statement

To modify the value of an array element, you must use the reference value assignment function.$valueAdd&.


  

Note! The$valueReference inforeachRetained after Loop. we recommend that you useunset()Destroy it.

list-each

In the example program, we also found a special traversal method calledlist-each.

WhenforeachWhen the execution starts, the pointer inside the array automatically points to the first unit, so you do not needforeachCalled before loopreset(). However,whileInlist-each, Array internal pointer$arrWill always exist, so we needreset($arr).

 

In the above code, the firstresetCan be omitted, but the secondresetIt cannot be saved.

list

PHP 5.5 adds the function of traversing an array and unpacks nested arrays into cyclic variables.

 

list()The number of elements in the array can be less than the number of nested arrays. If there are more than one, an error message will be sent.

break

breakUsed to end the currentfor/foreach/while/do-while/switchStructure execution.breakYou can accept an optional numeric parameter to determine the number of loops that exit, but the parameter cannot be a variable.

breakJumping out of multiple loops is the first time I encountered it. I wrote a small program and tried it.

 

I tried it in the C language and prompted a syntax error.

continue

AndbreakSimilar,continueYou can also accept an optional numeric parameter to skip several repeated loops to the end of the loop.

Note! In PHPswitchStatement is considered usablecontinue.

switch

The manual says that PHP is different from other languages,continueStatementswitchSimilarbreak. What does this mean?

switch/caseWhat we do is loose comparison.==Instead of strict comparison===. Efficiency,switchThe condition in the statement is evaluated only once and used together with eachcaseStatement comparison.caseAn expression can be a simple expression and cannot be an array or an object. Use semicolons insteadcaseThe colon after the statement.

declare

declareThe structure is used to set the execution instructions of a piece of code. the syntax structure is as follows:

declare(directive)statement

directivePartially AlloweddeclareCode snippet behavior. Currently, only two commands are known:ticksAndencoding.declareThe structure can also be used globally to affect all codes after expiration. However, ifdeclareIf a structure file is contained by another file, it does not work for the parent file containing it.

Tick (clock cycle) isdeclareEvents that occur when the interpreter executes N low-level statements that can be timed. Events that occur in each tick are composedregister_tick_function(). The usage is roughly as follows.

declare(ticks = 1);functiontick_handler(){echo"tick_hander() called.\n";}register_tick_function('tick_hander');

There are many low-level statements that can be timed,register_tick_function()A periodic event is called. a periodic event is called after each statement, and a periodic event is called at the end of curly braces.

Note: expressions in PHP cannot be separated by commas. Otherwise, a syntax error occurs. This is different from the C language, just noticed.

You can use the encoding command to specify the encoding method for each script. The usage is as follows:

declare(encoding = 'ISO-8859-1);

return

If it is called globally, the current script file stops running. If the current script file isincludeOrrequireTo control the call back file. If the current script isinclude, ThenreturnWill be treatedincludeThe return value of the call.requireWhat about it?

require

requireAndincludeAlmost exactly the same, except for the failure handling method.

requireGenerated when an error occursE_COMPILE_ERRORLevel error. the script is aborted. WhileincludeGenerate only warningsE_WARNING, The script continues to be executed.

include

includeThe statement contains and runs the specified file. pay attention to the search order of the specified file.

  • The contained file is first searched based on the path given by the parameter. If the path is defined,include_pathWill be completely ignored.
  • If no directory (only file name) is providedinclude_pathFind the specified directory. If it is not found, you can find it in the directory where the script file is called and in the current working directory. So the question is, what is the difference between the directory where the script file is called and the current working directory?
  • If the file is still not foundincludeStructure will issue a warning,requireStructure will send a fatal error.

When a file is contained, the code contained in the file inheritsincludeThe variable range of the row. From this point on, variables defined in the called file can be used in the call file. When a file is contained, the parser disconnects the target file from the PHP mode and enters the HTML mode. when the file ends, the parser replies.

For the return valueincludeReturnFALSEAnd issue a warning. If a successful inclusion is successful, 1 is returned unless the returned value is provided in the contained file. If a function is defined in the include filereturnPreviously defined and later versions can be used independently in the master file.

If the file from the remote server should be run at the remote end and only the result is output, usereadfile()Better functions. Another way to include a php file into a variable is to combine the output control functionsincludeTo capture its output. The first time I met, it was a stranger. The following code can replace the scriptvars.php.

 

BecauseincludeAndrequireIt is a special language structure, and its parameters do not need parentheses. If the file is contained twice, PHP will issue a fatal error because the function has been defined. Recommendedinclude_once.

require_once

require_onceStatement andrequireThe statement is identical. The only difference is that PHP checks whether the file has been included. if so, PHP does not include the file again.

include_once

include_onceStatement andincludeThe statement is similar. The only difference is that if the file has been included, it will not be included again.

goto

gotoThe operator is used to jump to another position of the program. the target position can be marked by a colon with the target name. In PHPgotoThe target location must be in the same file and scope. That is to say, you cannot jump out of a function or class method, or jump into any loop orswitchStructure.

(Full text)

Process control and implementation methods in PHP speech

A script is composed of statements. statements are implemented by flow control. This section describes the use of several keywords.

Elseif

elseifAndelse ifThe behavior is exactly the same. if you use a colon to defineif/elseifCondition, you cannot use two words.else ifOtherwise, PHP will produce a parsing error.


     $b) :echo"$a is greater than $b";elseif($a == $b) :echo"$a equals $b";else :echo"$a is neither greater than or equal to $b";endif;

Alternative syntax

The following keywords can use the alternative syntax of flow control. The basic form is to replace left curly braces with colons, and right curly braces with the following characters.

if - endifwhile - endwhilefor - endforforeach - endforeachswitch - endswitch

Note! PHP does not support mixing two syntaxes in the same control block.

Do-while

This loop seems familiar, but ignores some of its usage.

As stated in the manual, senior C language users may be familiar with another differentdo-whileLoop usage, put the statement indo-while(0). I have heard of this kind of technique for the first time. it seems that I am still a little white in C language.

Search and sort it out.do-while(0)Advantages of this special usage.

  1. Code chunks are more intuitive than just curly braces.
  2. UsebreakSkip the remaining code.
  3. It is helpful for macro-defined functions. when using a function, you can add points at the end of a sentence, which looks more like a function call.
  4. Block-level scope to prevent variable names from spreading to the upper-level scope.
  5. DeformedgotoStatement.

This post is quite good. The role of do {} while (0)-c ++-SegmentFault.

Huai 'an quail egg download (http://www.gamefrye.com /)

Foreach

foreachIt can only be applied to the traversal of arrays and objects.foreachThe syntax structure provides a simple way to traverse arrays. There are two types of syntax.

foreach(array_expression as$value)statementforeach(array_expression as$key => $value)statement

To modify the value of an array element, you must use the reference value assignment function.$valueAdd&.


    

Note! The$valueReference inforeachRetained after Loop. we recommend that you useunset()Destroy it.

list-each

In the example program, we also found a special traversal method calledlist-each.

WhenforeachWhen the execution starts, the pointer inside the array automatically points to the first unit, so you do not needforeachCalled before loopreset(). However,whileInlist-each, Array internal pointer$arrWill always exist, so we needreset($arr).

 

In the above code, the firstresetCan be omitted, but the secondresetIt cannot be saved.

list

PHP 5.5 adds the function of traversing an array and unpacks nested arrays into cyclic variables.

 

list()The number of elements in the array can be less than the number of nested arrays. If there are more than one, an error message will be sent.

break

breakUsed to end the currentfor/foreach/while/do-while/switchStructure execution.breakYou can accept an optional numeric parameter to determine the number of loops that exit, but the parameter cannot be a variable.

breakJumping out of multiple loops is the first time I encountered it. I wrote a small program and tried it.

 

I tried it in the C language and prompted a syntax error.

continue

AndbreakSimilar,continueYou can also accept an optional numeric parameter to skip several repeated loops to the end of the loop.

Note! In PHPswitchStatement is considered usablecontinue.

switch

The manual says that PHP is different from other languages,continueStatementswitchSimilarbreak. What does this mean?

switch/caseWhat we do is loose comparison.==Instead of strict comparison===. Efficiency,switchThe condition in the statement is evaluated only once and used together with eachcaseStatement comparison.caseAn expression can be a simple expression and cannot be an array or an object. Use semicolons insteadcaseThe colon after the statement.

declare

declareThe structure is used to set the execution instructions of a piece of code. the syntax structure is as follows:

declare(directive)statement

directivePartially AlloweddeclareCode snippet behavior. Currently, only two commands are known:ticksAndencoding.declareThe structure can also be used globally to affect all codes after expiration. However, ifdeclareIf a structure file is contained by another file, it does not work for the parent file containing it.

Tick (clock cycle) isdeclareEvents that occur when the interpreter executes N low-level statements that can be timed. Events that occur in each tick are composedregister_tick_function(). The usage is roughly as follows.

declare(ticks = 1);functiontick_handler(){echo"tick_hander() called.\n";}register_tick_function('tick_hander');

There are many low-level statements that can be timed,register_tick_function()A periodic event is called. a periodic event is called after each statement, and a periodic event is called at the end of curly braces.

Note: expressions in PHP cannot be separated by commas. Otherwise, a syntax error occurs. This is different from the C language, just noticed.

You can use the encoding command to specify the encoding method for each script. The usage is as follows:

declare(encoding = 'ISO-8859-1);

return

If it is called globally, the current script file stops running. If the current script file isincludeOrrequireTo control the call back file. If the current script isinclude, ThenreturnWill be treatedincludeThe return value of the call.requireWhat about it?

require

requireAndincludeAlmost exactly the same, except for the failure handling method.

requireGenerated when an error occursE_COMPILE_ERRORLevel error. the script is aborted. WhileincludeGenerate only warningsE_WARNING, The script continues to be executed.

include

includeThe statement contains and runs the specified file. pay attention to the search order of the specified file.

  • The contained file is first searched based on the path given by the parameter. If the path is defined,include_pathWill be completely ignored.
  • If no directory (only file name) is providedinclude_pathFind the specified directory. If it is not found, you can find it in the directory where the script file is called and in the current working directory. So the question is, what is the difference between the directory where the script file is called and the current working directory?
  • If the file is still not foundincludeStructure will issue a warning,requireStructure will send a fatal error.

When a file is contained, the code contained in the file inheritsincludeThe variable range of the row. From this point on, variables defined in the called file can be used in the call file. When a file is contained, the parser disconnects the target file from the PHP mode and enters the HTML mode. when the file ends, the parser replies.

For the return valueincludeReturnFALSEAnd issue a warning. If a successful inclusion is successful, 1 is returned unless the returned value is provided in the contained file. If a function is defined in the include filereturnPreviously defined and later versions can be used independently in the master file.

If the file from the remote server should be run at the remote end and only the result is output, usereadfile()Better functions. Another way to include a php file into a variable is to combine the output control functionsincludeTo capture its output. The first time I met, it was a stranger. The following code can replace the scriptvars.php.

 

BecauseincludeAndrequireIt is a special language structure, and its parameters do not need parentheses. If the file is contained twice, PHP will issue a fatal error because the function has been defined. Recommendedinclude_once.

require_once

require_onceStatement andrequireThe statement is identical. The only difference is that PHP checks whether the file has been included. if so, PHP does not include the file again.

include_once

include_onceStatement andincludeThe statement is similar. The only difference is that if the file has been included, it will not be included again.

goto

gotoThe operator is used to jump to another position of the program. the target position can be marked by a colon with the target name. In PHPgotoThe target location must be in the same file and scope. That is to say, you cannot jump out of a function or class method, or jump into any loop orswitchStructure.

(Full text)

The above introduces the process control and implementation methods in PHP speech, including some content, and hopes to help those who are interested in PHP tutorials.

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.