1
votes

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 ?

1
There is a solution for C and C++, which does not work in PHP. This is a PHP question, not a C or C++ question. Removing the tags. - Leandros
@Leandros Thanks for your help. Out of curiosity, what's the solution for C and C++ ? - Ewan Delanoy
goto. It's a commonly used solution. - Leandros
php 5.3+ does have goto - Jonathan Kuhn

1 Answers

1
votes

In your case, you can either use goto (since PHP 5.3) or by adding another simple check.

$loopcheck = true;
for($i=1;some_test($i) && $loopcheck;$i++) {
       for($j=1;some_test($j) && $loopcheck;$j++) {
          for($k=1;some_test($k) && $loopcheck;$k++) {
             if(unicorn_test_for_three_parameters($i,$j,$k))  {
              $searchResult = array($i,$j,$k);
              $loopcheck = false;
              break;
             }
          }
          if(unicorn_test_for_two_parameters($i,$j)) {
            $searchResult = array($i,$j);
            $loopcheck = false;
            break;
           } 
       }
       if(unicorn_test_for_one_parameter($i)){
            $searchResult = array($i);
            $loopcheck = false;
        } 
   }