PHP return 語句
介紹
PHP 中 **return** 語句的目的是將程式執行控制權返回到呼叫它的環境。返回後,繼續執行呼叫其他函式或模組的表示式之後的內容。
如果 return 語句出現在函式內部,則當前函式的執行將終止,並將控制權返回到呼叫它的環境。return 語句前面可以有一個可選的表示式。在這種情況下,表示式的值也會連同控制權一起返回。
如果在 **包含** 的指令碼中遇到 return 語句,則當前指令碼的執行將立即結束,控制權將返回到包含它的指令碼。如果它出現在頂層指令碼中,則執行將立即結束,並將控制權返回給作業系統。
函式中的 return
下面的例子展示了函式中的 return 語句
示例
<?php
function SayHello(){
echo "Hello World!
";
}
echo "before calling SayHello() function
";
SayHello();
echo "after returning from SayHello() function";
?>輸出
這將產生以下結果:
before calling SayHello() function Hello World! after returning from SayHello() function
帶值的 return
在下面的例子中,一個函式返回一個表示式。
示例
<?php
function square($x){
return $x**2;
}
$num=(int)readline("enter a number: ");
echo "calling function with argument $num
";
$result=square($num);
echo "function returns square of $num = $result";
?>輸出
這將產生以下結果:
calling function with argument 0 function returns square of 0 = 0
在下一個例子中,包含了 test.php,並且它有 return 語句,導致控制權返回到呼叫指令碼。
示例
//main script <?php echo "inside main script
"; echo "now calling test.php script
"; include "test.php"; echo "returns from test.php"; ?> //test.php included <?php echo "inside included script
"; return; echo "this is never executed"; ?>
輸出
當主指令碼從命令列執行時,將產生以下結果:
inside main script now calling test.php script inside included script returns from test.php
包含檔案中也可以在 return 語句前面有一個表示式。在下面的例子中,包含的 test.php 將一個字串返回給主指令碼,主指令碼接收並列印它的值。
示例
//main script <?php echo "inside main script
"; echo "now calling test.php script
"; $result=include "test.php"; echo $result; echo "returns from test.php"; ?> //test.php included <?php $var="from inside included script
"; return $var; ?>
輸出
這將產生以下結果:
inside main script now calling test.php script from inside included script returns from test.php
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP