在php函数内部返回后需要退出


Is exit needed after return inside a php function?

<?php
function testEnd($x) {
    if ( ctype_digit($x) ) {
        if ( $x == 24 ) {
            return true;
            exit;
        } else {
            return false;
                 exit;
        }
    } else {
        echo 'If its not a digit, you''ll see me.';
        return false;
        exit;
    }
}
$a = '2';
if ( testEnd($a) ) {
    echo 'This is a digit';
} else {
    echo 'No digit found';
}
?>

在php函数中使用它们时,是否需要exit和return ?在这种情况下,如果任何计算结果为false,我希望在那里结束并退出。

不需要。当你从一个函数返回时,之后的任何代码都不会执行。如果它确实执行了,那么你的could就会停在那里,也不会回去调用function。exit应该是

根据PHP手册

如果从函数内部调用,立即返回语句结束当前函数的执行,并返回其参数为函数调用的值。Return也将结束执行eval()语句或脚本文件。

然而,退出,根据PHP手册

终止脚本的执行。

如果你的exit真的在执行,它会在这里停止所有的执行

编辑

举一个小例子来演示exit的作用。假设你有一个函数,你想简单地显示它的返回值。那么试试这个

<?php
function test($i)
{
    if($i==5)
    {
        return "Five";
    }
    else
    {
        exit;
    }
}

echo "Start<br>";
echo "test(5) response:";
echo test(5);
echo "<br>test(4) response:";
echo test(4); 
/*No Code below this line will execute now. You wont see the following `End` message.  If you comment this line then you will see end message as well. That is because of the use of exit*/

echo "<br>End<br>";

?>