简体   繁体   English

在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';
}
?>

Is exit needed along with return when using them inside a php function? 在php函数中使用它们时是否需要退出以及返回? In this case, if anything evaluated to false, i'd like to end there and exit. 在这种情况下,如果任何评估为false,我想结束并退出。

No it's not needed. 不,不需要它。 When you return from a function then any code after that does not execute. 从函数返回时,之后的任何代码都不会执行。 if at all it did execute, your could would then stop dead there and not go back to calling function either. 如果它确实执行了,那么你可以在那里停止死亡而不是回到调用函数。 That exit should go exit应该去

According to PHP Manual 根据PHP手册

If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. 如果在函数内调用,则return语句立即结束当前函数的执行,并将其参数作为函数调用的值返回。 return will also end the execution of an eval() statement or script file. return也将结束eval()语句或脚本文件的执行。

Whereas, exit , according to PHP Manual 然而, 退出 ,根据PHP手册

Terminates execution of the script. 终止脚本的执行。

So if your exit was really executing, it would stop all the execution right there 因此,如果您的出口确实正在执行,它将在那里停止所有执行

EDIT 编辑

Just put up a small example to demonstrate what exit does. 只是举一个小例子来证明退出的作用。 Let's say you have a function and you want to simply display its return value. 假设您有一个函数,并且您只想显示其返回值。 Then try this 然后尝试这个

<?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>";


?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM