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