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