PHP goto

 PHP goto is used to perform the task of program jump. When writing C language, goto is a commonly used technique, but it is not commonly used in PHP . Goto has some restrictions in PHP , and it can only be in a certain context in the same file. , Which means that you cannot jump out of the same file, function or method to execute other programs, and of course you cannot jump into another file, function or method. Although the restriction is stricter than in the C language, it is used to jump out of the loop or The switch is quite convenient. The concept of goto has been used in C language for a long time, and PHP, which is derived from C language, finally has this concept. The development of PHP is really getting stronger and stronger.


PHP goto syntax example
<?php
goto section2;
echo 'section1';

section2:
echo 'section2';
?>
Output result
section2
The first line of the example uses the technique of goto to section2, so the PHP program will automatically skip the echo'section1' step of the next line and proceed to the code below section2:. Please note that section2 must be followed by a semi-colon, so PHP I knew how to go.

PHP goto out of the loop example
<?php
for ( $i=0 ; $i<20 ; $i++ ){
 if( $i==5 ) goto END;
}
echo " i = $i ";

END:
echo ' 變數 i 達到 5 囉!';
?>
Output result
The variable i reaches 5!
In this example, we first designed a simple PHP for loop , which is expected to run from 0 to 19, and then add an if judgment formula to the for loop. When the variable $i reaches 5, goto will be executed and the program will be taken to The END: block is equivalent to forcibly jumping out of the for loop. (Related reference: PHP break usage ).

Note: PHP goto can only be used on PHP 5.3 and newer versions.

Post a Comment

0 Comments