Is there any way out after returning inside the 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 a return exit required when using them inside a php function? In this case, if something evaluates to false, I would like to finish the job and exit.

+4
source share
1 answer

No, it is not necessary. When you return from a function, any code after that is not executed. if it does at all, yours could then stop there and not return to the calling function. This exit should go

According to PHP Manual

If called inside a function, the return statement immediately terminates the execution of the current function and returns its argument as the value of the function call. return will also end the execution of the eval () or script statement.

While exit , according to the PHP Manual

Terminates the execution of the script.

So, if your exit was actually executing, it would stop all execution right there

EDIT

Just give a small example to demonstrate what exit does. Say you have a function and you just want to 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>"; ?> 
+28
source

Source: https://habr.com/ru/post/1481874/


All Articles