The goto operator is added after PHP5.3 +. It is used to jump to another position of the program. Its usage is simple: The goto operator is followed by the target position mark, and the target name is marked with a colon, as shown below:
Copy codeThe Code is as follows:
Goto;
Echo 'feet home ';
A:
Echo 'HTTP: // www.jb51.net ';
However, the target location of goto can only be the same file and scope [Neither jump to a function or class method]. Of course, it can jump out of the loop, but cannot jump into the loop:
Copy codeThe Code is as follows:
<? Php
For ($ I = 0; $ I <3; $ I ++)
{
Echo $ I. '<br> ';
If ($ I = 1) goto end;
}
End:
Echo 'end ended directly ';
The goto operator can be used to jump to a specified position in the program. You can add a colon to the target location. PHP has certain restrictions on goto. You can only jump to the same file and scope. That is to say, you cannot jump out of one function or class method, or jump to another function. You cannot jump into any loop or switch structure. A common usage is to jump out of a loop or switch, which can replace multiple levels of break.
Copy codeThe Code is as follows:
<? Php
Goto;
Echo 'foo ';
A:
Echo 'bar ';
?>
The above routine will output: Bar
Goto skip loop example
Copy codeThe Code is as follows:
<? Php
For ($ I = 0, $ j = 50; $ I <100; $ I ++ ){
While ($ j --){
If ($ j = 17) goto end;
}
}
Echo "I = $ I ";
End:
Echo 'J hit 17 ';
?>
The above routine will output: j hit 17
The following statement is invalid.
Copy codeThe Code is as follows:
<? Php
Goto loop;
For ($ I = 0, $ j = 50; $ I <100; $ I ++ ){
While ($ j --){
Loop:
}
}
Echo "$ I = $ I ";
?>
The above routine will output:
Fatal error: 'Goto 'into loop or switch statement is disallowed in
Script on line 2