php5.3 Goto Function Introduction and Example _php instance

Source: Internet
Author: User
Tags goto

The goto operator is a new feature added after php5.3+ to jump to another location in the program; the usage is simple: goto followed by a flag with the target location, with a colon marked at the destination, as follows:

Copy Code code as follows:

Goto A;
Echo ' cloud-dwelling community ';
A:
Echo ' http://www.jb51.net ';

But Goto destination can only be the same file and scope "can not jump to a function and class method", of course, it can jump out of the loop, but can not jump into the loop:

Copy Code code as follows:

<?php
for ($i = 0; $i < 3; $i + +)
{
Echo $i. ' <br> ';
if ($i = = 1) goto end;
}
End:
Echo ' Straight end ';

The goto operator can be used to jump to a specified position in a program. The target location can be marked with a colon for the target name. The Goto in PHP has a certain limit and can only jump in the same file and scope, which means you can't jump out of a function or class method, and you can't skip to another function. You also can't jump into any loops or switch structures. A common use is to jump out of loops or switch, instead of multiple layers of break.

Copy Code code as follows:

<?php
Goto A;
Echo ' Foo ';

A:
Echo ' Bar ';
?>

The above routine will output: Bar

Goto Jump Out Loop Example

Copy Code code 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 wording is not valid

Copy Code code as follows:

<?php
Goto Loop;
For ($i =0, $j =50 $i <100; $i + +) {
while ($j-) {
Loop
}
}
echo "$i = $i";
?>

The above routines will output:

Fatal error: ' Goto ' into loop or switch statement are disallowed in
Script on line 2

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.