Toplevel equivalent in PHP of "return" keyword outside function blocks ?
A nice, useful property of the return keyword is that when it is invoked,
it exits the main function block in which it is, no matter how many other
nested blocks may surround it.
I am not aware of any equivalent for the toplevel scope. And I would like
to have a systematic way of "expanding" a function
call into an equivalent list of statements, and for that I need to know
a systematic way to deal with all the return ’s in the code.
Consider for example
function seekAUnicorn()
{
for($i=1;some_test($i);$i++) {
for($j=1;some_test($j);$j++) {
for($k=1;some_test($k);$k++) {
if(unicorn_test_for_three_parameters($i,$j,$k)) return(array($i,$j,$k));
}
if(unicorn_test_for_two_parameters($i,$j)) return(array($i,$j));
}
if(unicorn_test_for_one_parameter($i)) return(array($i));
}
}
The expansion of $searchResult=seekAUnicorn(); might look something like this :
for($i=1;some_test($i);$i++) {
for($j=1;some_test($j);$j++) {
for($k=1;some_test($k);$k++) {
if(unicorn_test_for_three_parameters($i,$j,$k)) {
$searchResult = array($i,$j,$k);
break 3;
}
}
if(unicorn_test_for_two_parameters($i,$j)) {
$searchResult = array($i,$j);
break 2;
}
}
if(unicorn_test_for_one_parameter($i)){
$searchResult = array($i);
break;
}
}
But to do it this way, you need to count the number of nested blocks around each nested return, which becomes painstaking and error-prone for longer and more complicated code. Is there a simpler way ?
goto. It's a commonly used solution. - Leandros