PHP goto 语句
简介
goto 语句用于将程序的流程发送到代码中的某个特定位置。该位置由用户定义的标签指定。通常,goto 语句作为条件表达式(例如 if、else 或 case(在 switch 结构中))的一部分出现在脚本中。
语法
statement1; statement2; if (expression) goto label1; statement3; label1: statement4;
在 statement2 之后,如果表达式(作为 if 语句的一部分)为真,则程序流程将定向到 label1。如果为假,则将执行 statement3。程序随后继续以正常流程执行。
在以下示例中,如果用户输入的数字为偶数,则程序跳转到指定的标签。
示例
<?php
$x=(int)readline("enter a number");
if ($x%2==0)
goto abc;
echo "x is an odd number";
return;
abc:
echo "x is an even number";
?>输出
这将产生以下结果:
x is an even number
goto 关键字前面的标签可以出现在当前语句之前或之后。如果 goto 语句中的标签标识了较早的语句,则它构成一个循环。
以下示例显示了一个使用 goto 语句构造的循环。
示例
<?php $x=0; start: $x++; echo "x=$x
"; if ($x<5) goto start; ?>
输出
这将产生以下结果:
x=1 x=2 x=3 x=4 x=5
使用 goto,程序控制可以跳转到任何命名位置。但是,不允许跳转到循环的中间。
示例
<?php
for ($x=1; $x<=5; $x++){
if (x==3)
goto inloop;
for ($y=1;$y<=5; $y++){
inloop:
echo "x=$x y=$y
";
}
}
?>输出
这将产生以下结果:
PHP Fatal error: 'goto' into loop or switch statement is disallowed in line 5
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP