<?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? In this case, if anything evaluated to false, i'd like to end there and exit.
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
According to PHP Manual
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 will also end the execution of an eval() statement or script file.
Whereas, exit , according to PHP Manual
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>";
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.