PHP返回声明
介绍
PHP中return语句的目的是将程序执行的控制权返回给调用它的环境。返回时,执行调用了其他函数或模块的表达式。
如果return语句出现在函数内部,则终止当前函数的执行,将控件移交给调用它的环境。return语句前面可能有一个exprssion作为可选子句。在这种情况下,除了控件之外,还返回表达式的值。
如果在包含的脚本中遇到,则当前脚本的执行将立即结束,控制权将返回包含它的脚本。如果在顶层脚本本身中找到它,则执行立即结束,将控件交还给OS。
返回一个函数
下面的示例显示函数中的return语句
示例
<?php
function SayHello(){
echo "Hello World!\n";
}
echo "before calling SayHello() function\n";
SayHello();
echo "after returning from SayHello() function";
?>输出结果
这将产生以下结果-
before calling SayHello() function Hello World! after returning from SayHello() function
值回报
在下面的示例中,一个函数返回一个表达式
示例
<?php
function square($x){
return $x**2;
}
$num=(int)readline("enter a number: ");
echo "calling function with argument $num\n";
$result=square($num);
echo "function returns square of $num = $result";
?>输出结果
这将产生以下结果-
calling function with argument 0 function returns square of 0 = 0
在下一个示例中,包含test.php并具有返回值,导致控制权返回到调用脚本。
示例
//main script <?php echo "inside main script\n"; echo "now calling test.php script\n"; include "test.php"; echo "returns from test.php"; ?> //test.php included <?php echo "inside included script\n"; return; echo "this is never executed"; ?>
输出结果
从命令行运行主脚本时,这将产生以下结果:
inside main script now calling test.php script inside included script returns from test.php
包含文件中的return语句前面也可以有一个表达式子句。在以下示例中,includedtest.php返回一个字符串到主脚本,该字符串接受并打印其值
示例
//main script <?php echo "inside main script\n"; echo "now calling test.php script\n"; $result=include "test.php"; echo $result; echo "returns from test.php"; ?> //test.php included <?php $var="from inside included script\n"; return $var; ?>
输出结果
这将产生以下结果-
inside main script now calling test.php script from inside included script returns from test.php
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短