Use of goto syntax in PHP

In C++, Java, and many other languages, there is a magic syntax called goto. As the name suggests, its use is to go directly to somewhere. From the point of view of the code, that is to jump directly to the specified place. We also have this feature in PHP, so let’s first look at how it works:

goto a;
echo "1"; // Do not output a:echo '2'; / / 2Copy the code

When the code runs to the goto position, it jumps to the line of code where a: is and continues. Fun to play with, this feature is useful for complex nested ifs or for jumping out of loops, especially for handling exceptions or error situations such as:

for ($i = 0, $j = 50; $i < 100; $i{+ +)while ($j-) {if ($j== 17) {// Suppose$j==17 is an abnormal case goto end; }}}echo "i = $i";
end:
echo 'j hit 17'; // Output or handle the exception directly hereCopy the code

It feels good, doesn’t it, but there are some limitations to goto grammar:

  • The target location can only be in the same file and scope, which means there is no way to jump out of one function or class method or jump into another
  • Unable to jump into any loop or switch structure
  • To break a loop or switch, the usual use is to use goto instead of multiple breaks

For example, the following code is invalid:

$a = 1;
goto switchgo;
switch ($a) {case 1:
        echo 'bb';
    break;
    case 2:
        echo 'cc';
        switchgo:
            echo "bb";
    break;
}

goto whilego;
while($a< 10) {$a+ +; whilego:echo $a;
}


// Fatal error: 'goto' to undefined label 'ifgo' 
Copy the code

They both report the same error because the defined GOto tag cannot be found by scope. Another thing to note is that using goto can cause an infinite loop, as shown below:

b:
    echo 'b';

goto b;
Copy the code

When the code goes to goto, it jumps back to the previous b tag line, and then continues down to goto again, becoming an infinite loop. It’s a little bit like while(true). However, there are no breaks in this goto loop, only when the goto goes out somewhere else.

As a result, the goto syntax is rarely used because it disrupts the logical flow of your code, but people who like it feel that it makes your code very flexible. This is a matter of choice, and most languages are not very well documented to use this syntax, including PHP. My advice is to avoid using goto syntax unless it’s very special or for show-off purposes. It’s easy to get confused when your project code gets complicated.

Test code: github.com/zhangyue050…

Reference: www.php.net/manual/zh/c…


Follow the public account: [Core project Manager] to get the latest articles



Add friends on wechat: DarkMatterZyCoder for free PHP learning materials