• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • return

    (PHP 4, PHP 5, PHP 7)

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

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

    更多信息见返回值。

    Note:注意既然return是语言结构而不是函数,因此其参数没有必要用括号将其括起来。通常都不用括号,实际上也应该不用,这样可以降低 PHP 的负担。

    Note:如果没有提供参数,则一定不能用括号,此时返回NULL。如果调用return时加上了括号却又没有参数会导致解析错误。

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

    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".
    Note that because PHP processes the file before running it, any functions defined in an included file will still be available, even if the file is not executed.
    Example:
    a.php
    <?php
    include 'b.php';
    foo();
    ?>
    b.php
    <?php
    return;
    function foo() {
       echo 'foo';
    }
    ?>
    Executing a.php will output "foo".

    上篇:declare

    下篇:require