开发者

Looping through several functions in PHP

开发者 https://www.devze.com 2023-01-18 23:23 出处:网络
Basically I want to achieve such functionality that 5-10 functions are executed in a row (like normally). However, I want the script to go back several steps back (ex. from 5th back to 3rd) and contin

Basically I want to achieve such functionality that 5-10 functions are executed in a row (like normally). However, I want the script to go back several steps back (ex. from 5th back to 3rd) and continue further (like 4,5,6,7,8,9,10), if specific return is received. Example:

<?
function_1st();
function_2nd();
function_3rd();
function_4th();
$a = function_5th();
if($a == '3') //continue from 3rd further;
function_6th();
function_7th();
?>

Like in this case it should be 开发者_如何学运维1,2,3,4,5,3,4,5,6,7,8,9,10. Would it be better to use object orientated programming (class) in this?

Basically I need only advice, how to make it like this in a proper waY :)

Regards, Jonas


wrap all the functions in a switch something like:

function run($n) {
    switch($n) {
      case 1: $a = func1(); break;
      case 2: $a = func2(); break;
      case 3: $a = func3(); break;
      case 4: $a = func4(); break;
      case 5: $a = func5(); break;
      case 6: $a = func6(); break;
      case 7: $a = func7(); break;
      case 8: $a = func8(); break;
      case 9: $a = func9(); break;
      default: return $a;
    }
    run($a ? $a : $n+1);
}


You could base the function calls on the previous function return

Example:

function one() {
   if()...
      return 'run function two';
   else 
      return 'run function four';
}


$step=1;
while($step < 99){
switch ($step){
    case 1:
        $step=function_1();
        break;
    case 2:
        $step=function_2();
        break;
    case 3:
        $step=function_3();
        break;
    ...
    case 9:
        $step=function_9();
        break;
    default:
        $step=99;
        }
    }


Use "variable functions" or "call_user_func() function". I don't have time to explain it, please google that keywords.


Why would you need to do this? Are you saying that the results on $a will be different if function_3() is called on it after function_5() has been called on it and then it will pass the check on function_5() ?

You may need to rethink your logic in general.

By the way, don't use short tags. Write out

<?php
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号