return

如果在一个函数中调用 return() 语句,将立即结束此函数的执行并将它的参数作为函数的值返回。return() 也会终止 eval() 语句或者脚本文件的执行。

如果在全局范围中调用,则当前脚本文件中止运行。如果当前脚本文件是被 include() 的或者 require() 的,则控制交回调用文件。此外,如果当前脚本是被 include() 的,则 return() 的值会被当作 include() 调用的返回值。如果在主脚本文件中调用 return(),则脚本中止运行。如果当前脚本文件是在 php.ini 中的配置选项 auto_prepend_file 或者 auto_append_file 所指定的,则此脚本文件中止运行。

更多信息见返回值

注: 注意既然 return() 是语言结构而不是函数,仅在参数包含表达式时才需要用括号将其括起来。当返回一个变量时通常不用括号,也建议不要用,这样可以降低 PHP 的负担。

注: 当用引用返回值时永远不要使用括号,这样行不通。只能通过引用返回变量,而不是语句的结果。如果使用 return ($a); 时其实不是返回一个变量,而是表达式 ($a) 的值(当然,此时该值也正是 $a 的值)。


add a note add a note User Contributed Notes
jasper at jtey dot com
26-May-2006 02:54
You can use alternate "if statement" syntax within a return statement itself:

<?php
// Return the minimum of two numbers
function min($a, $b){
  return
$a < $b ? $a : $b;
}
?>
warhog at warhog dot net
19-Dec-2005 04:28
for those of you who think that using return in a script is the same as using exit note that: using return just exits the execution of the current script, exit the whole execution.

look at that example:

a.php
<?php
include("b.php");
echo
"a";
?>

b.php
<?php
echo "b";
return;
?>

(executing a.php:) will echo "ba".

whereas (b.php modified):

a.php
<?php
include("b.php");
echo
"a";
?>

b.php
<?php
echo "b";
exit;
?>

(executing a.php:) will echo "b".
mike at uwmike dot com
07-Dec-2005 01:25
If you have a class file that's getting out of control, you can set it up like so:

<?php
class myClass {
  function
do_this($a, $b) { return require(myClass_do_this.php); }
  function
do_that($a, $b, $c) { return require(myClass_do_that.php); }
}
?>

Might not be for everyone, but it's workable, readable, and keeps the source files shorter.
11-Aug-2005 10:42
If you like pickles, then it's good for you.
PackCat
11-Jun-2005 09:02
If you return a value that has not been set, or has been unset, the function will return that status instead. So,

<?php
$var1
= 1;
function
unsetVar($var) {
   unset(
$var);
   return
$var;
}
$var1 = unsetVar($var1); // this will unset $var1
?>

This is useful in situations where we want to conditionally proceed based on the output of a function; for example,
if (isset($fileListAsArray = functionGettingFileList())) {
   // our list exists, do whatever
} else . . . // report error
24-May-2005 11:44
If you are just wanting to get the current output printed to the browser (and continue execution), use flush().
17-Feb-2003 07:04
Use "exit()" to end all script execution for the current request. For HTTP requests, the response generated to that point will then be sent to the browser.