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

在php函數中使用它們時是否需要退出以及返回? 在這種情況下,如果任何評估為false,我想結束並退出。

不,不需要它。 從函數返回時,之后的任何代碼都不會執行。 如果它確實執行了,那么你可以在那里停止死亡而不是回到調用函數。 exit應該去

根據PHP手冊

如果在函數內調用,則return語句立即結束當前函數的執行,並將其參數作為函數調用的值返回。 return也將結束eval()語句或腳本文件的執行。

然而, 退出 ,根據PHP手冊

終止腳本的執行。

因此,如果您的出口確實正在執行,它將在那里停止所有執行

編輯

只是舉一個小例子來證明退出的作用。 假設您有一個函數,並且您只想顯示其返回值。 然后嘗試這個

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